Posted on by & filed under Content - Highlights and Reviews, Programming & Development.

The .NET Entity Framework (EF) is an object-relational database mapper that enables easy database access for .NET developers using domain-specific .NET objects that EF can generate for you. As we saw in my last blog post on Entity Framework, you can use EF to automatically create your application’s database from the classes you have in your code. It can even be used to migrate your database to newer versions as you add columns to your database or even add default rows when it first creates the database. While we won’t go into those features here, it helps to know that all that database goodness is available to you.

In my last blog post we used EF to create a SeminarContext database, and then, using the console application that we created, we added and displayed the rows in the database. We will be using that same database as the basis for this blog post so if you haven’t done so yet, you may want to read the previous post and work through that code.

In the real world of application development we don’t always get the luxury of starting from scratch. Rather, we often have to code against an existing database. Read 2-2. Creating a Model from an Existing Database from Entity Framework 4.0 Recipes: A Problem-Solution Approach to see how to create a model from an existing database. Here again, the Entity Framework comes to our rescue by “reading and analyzing” our existing database and then generating the code we need to access the database for all CRUD operations. It saves the developer a lot of database coding that they had to do in the past by generating a consistent set of classes so that all of our database applications can do things in a similar manner that makes it easier for the developer to maintain. So, let’s get started.

First, open Visual Studio (I’m using VS 2012) and create a new Windows Console project, calling it “SafariDatabaseFirst.”

Now that we have our application created we are going to use the Entity Framework Power Tools to generate some code and a map to our existing database. Right-click on your project in Solution Explorer and select Entity Framwork -> Reverse Engineer Code First. If you don’t see the option, then you will need to install the EF Power Tools and restart Visual Studio. Next, enter the connection details for your existing database and click OK. In my case, I am using localDb, but your database may be in SQLEXPRESS so use the appropriate connection. Either way, you will need to specify the server and the database.

After clicking OK, Visual Studio will add Entity Framework to your project and then reverse engineer the database. The status bar at the bottom of Visual Studio will keep you updated on the progress. Once finished, you will see a couple of new folders in Solution Explorer along with some new C# source files.

There will also be a new app.config added to your project that contains the database connection string:

EF created a Models and a derived Context class for each table in the database. In the code you can see that EF created a DbSet<TEntity> for each type (think database table) in our model. You may remember using DbContext and DbSet in the first blog post and they are what allows us to query and update our data.

Pay attention to the default constructor and that it calls a base constructor using a ‘name=’ syntax, as that is very important for two reasons.

First, it tells Code First to load the connection string to use from the configuration file. Second, it ensures that if the connection string isn’t found that Entity Framework will throw an error rather than creating a new database. You should always use the ‘name=’ syntax when using a connection string from the config file to prevent unwanted databases from popping up all over the place.

The Models folder also now contains source code files for the domain classes (Seminar.cs & Topic.cs) for the model. In the Models\Mapping folder you will find configuration classes that handle the mapping to the database. Again, you will find maps for each table in the database.

Now that we have briefly looked at what EF has generated for us, it is time to put all of that generated code to good use. In Program.cs, add the following code so that we can add rows to our database and then list them out. If you followed the first blog post, you will notice that this code is very similar to what we used in that post.

First we add the following line to the top of the code so that we can use the model:

Then in the Main() method we need to add what is shown below:

Looking at the code you can see that first we create a new instance of the context (think database session/connection) using the EF generated context, and we use it to insert a new Seminar. After we put some data into the database, we will run a LINQ query to retrieve all of the records in the database. Notice that we wrap our code in a using statement so that all of our resources will get cleaned up.

Our console application should now be ready to compile and run.

Notice that we added “Seminar 5” to the database, but since Entity Framework modeled our existing database and used it for our data connection, we also see the seminars we added from the previous blog post.

Entity Framework generated all of the plumbing code and we really only wrote a small amount of code to make all this work. That is the power and beauty of using Entity Framework.

Safari Books Online has the content you need

Check out these .NET Entity Framework books available from Safari Books Online:

Entity Framework 4.0 Recipes: A Problem-Solution Approach provides an exhaustive collection of ready-to-use code solutions for Microsoft’s Entity Framework, Microsoft’s vision for the future of data access. Entity Framework is a model-centric data access platform with an ocean of new concepts and patterns for developers to learn. With this book, you will learn the core concepts of Entity Framework through a broad range of clear and concise solutions to everyday data access tasks. Armed with this experience, you will be ready to dive deep into Entity Framework, experiment with new approaches, and develop ways to solve even the most difficult data access challenges.
Programming Entity Framework: Code First acts as an extension to Programming Entity Framework 2nd Edition. Code First is an additional means of building a model to be used with the Entity Framework and is creating a lot of excitement in the .NET development community. The book begins with an overview of what Code First is, why it was created, how it fits into the Entity Framework and when to use it over the alternatives.
Entity Framework 4.1: Expert’s Cookbook holds many examples to help guide you through tough technical decisions and avoid technical landmines. The book will guide you from just using Entity Framework to enhancing the data access wizard. You will be guided through complex mapping scenarios, query definition, reusability, integration with other technologies, and architectural management. The approach is step-by-step and test driven so that it is focused as much as possible on solving problems and getting the most out of the time spent working through the book.

About the author

Marshall Harrison is the founder of GotSpeech.Net and as well as the owner and CEO of GotSpeech Consulting LLC. He holds a B.S. degree in Computer Science and was a Microsoft MVP from 2006 – 2011. He is currently focusing on Microsoft Lync as well as Windows 8 and Windows Phone 8 devleopment. He can be reached through his blog at

Tags: .NET Entity Framework, C#, CRUD, database, EF, Visual Studio 2012,

Comments are closed.