Code First Approach in Entity Framework

This article explains more about the Code First approach. This one is my personal favorite. In the previous exlanations I made the models using the EF designer. In the first case what I did is reverse engineer an existing database into a model and then I created a model right from scratch in the designer and then created the database. So, basically in both the cases, the designer generated the code. Some of us really like to work with designers. But there are also no huge followers that just love to stick to code and work from there itself. So, for this case, we have the other approach of the "Code First Approach". So, let's get started.

Let's start with some of its features.

  • Code First has the ability to use the model classes written by the user and create it as a table in the database.

  • It also has the ability to update the database if any of the model classes are changed or any new class is added using Code First Migrations feature.

Migrations feature

So, in the preceding screen shot I have many sample classes. You could also see that it has one navigation property with the OrderDetails class so that it can build a relationship with the Orders class. So, these are some classes that will play a crucial role in Code First in the EF.

So to use these classes, I am making one more layer just to make things tidy in the same solution with the name DAL (Data Access Layer) and then subsequently I'll add references to this class library project. When I said references I mean EF references as shown below.

class

manage nuget package

install entityframwork

EF install

So, now we have successfully added the EF references to the project. It has also added App.config and packages.config files just to make the proper configurations for the EF in there.

app

Now, since all the configurations are in place, I can go ahead and get started with the context class and inherit it from the DbContext class.

DbContext

So, DbContext is a class that undersstands the EF Code First approach and to understand my model classes, I need to convert it in DbSet. So, basically a DbSet of these model classes will allow the EF to manage objects or to allow any kind of CRUD operation required in the application. To do that first I need to reference my model classes to the DAL layer so that it can be exposed.

model

Now, one important point I would like to point out here is, in order to validate your data model, you must validate it against the designer, whether the desired diagram is generating or not. In order to do that, first what you need to do is to import one tool from the Extensions and Updates option. You need to just type "Entity Framework Power Tools" as shown below and then install it. After installation Visual Studio might ask you to restart the IDE so that the tool can take effect.

Entity Framework Power Tools

As you see in the preceding in snapshot, I have already installed that tool. Now, to validate the data model what you need to do first is be sure that your DAL layer is marked as the Startup Project, just to avoid the connection string error. And then do the following as shown below.

view empty data

Now, when you do that it might throw an error if any are present, like if a class hasn't been annotated with the [Key] attribute because the EF won't understand what is the key in the class. And if everything goes well, it will generate the diagram as shown below.

generate the diagram

So, this was the diagram that was supposed to be generated. This is a fairly simple model based on the class relationship. You could see it in the diagram that the first two entities have a relationship and the other two are independent, I made the same way just to keep the things simple.

Now, another important concept one should understand is that Code First doesn't bother about the database until runtime. So, this happens in two steps. First it locates the database and the second step is to create the database if required.

Now, let's start doing a demonstration with one little console app wherein I'll be exposing the context to walk through one of the tables and print the result as shown below.

program

Now, when I run the app, you can see in the side screen that DAL.SampleModel has been created. Currently, there won't be any data inside. So we need to seed the data in there to populate on the screen.

table

So, it may happen that if you are going to run the app again it would throw you an exception. The reason being is that the default behavior restricts the user for database initialization to one time, however we can override it using certain configuration changes, because if our model changes then we need to update the database as well. So what we can do here is, instead of using an initialization every time, we can use database migrations. So I need to go into the Package Manager Console and from there I need to enable database migrations as shown below.

package manager console

migration

code

configuration

So now that the migrations are enabled, we need to specifically set the option of the one I will use for the migrations out of the 4 as listed below.

  • CreateDatabaseIfNotExists --> This is the default
  • DropCreateDatabaseIfModelChanges
  • DropCreateDatabaseAlways
  • MigrateDatabaseToLatestVersion

So, these are the four options, so I will use the last one, because in this scope it suits me.

MigrateDatabaseToLatestVersion

Now the next step is to seed the database. So, basically I can mock some data, either manually by directly entering the data into tables or via code. So when we use the code approach, we call this seeding of the database. So to do that we'll override the configuration Seed method by changing the commented part as shown below.

changing the commented part

added two records

So, in the preceding screen shot, I have added two records via the seed method. Seeding is really useful when you want to test your app against some mock data before it is being promoted to production just to get the feel of the real app.

Now, when I run my app and step through it, it should produce these two record sets in the console screen as shown below.

cmd

Now, with this I would like to wrap up this module. I have also attached the sample code for your reference. Until then stay tuned and Happy Coding.

Download Link: Sample Code

Thanks,
Rahul
Happy Coding.

Up Next
    Ebook Download
    View all
    Learn
    View all