Today in this discussion, we’ll see more about code first approach. This one is my personal favorite. In the previous discussions I made the models using the EF designer. In the 1st case what i did is reverse engineered an existing database into model and then i created a model right from scratch in the designer and then created the database. So, basically in both the cases, designer generates the code. some of us really like to work with designers. But, there are also huge no of followers who just love to stick to code and work from there itself. So, for this case, we have another approach “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 user and create the same as table in the database.
- It has also got the ability to update the database if any of the model classes gets changed or any new class added using Code First Migrations feature.
so, in the above screen shot i have got a bunch of sample classes. Also you could see it has got one navigation property with OrderDetails class so that it can build relationship with Orders class. so, these are some classes which is going to play crucial role in code 1st EF.
So, in order to make use of these classes i’ll be making one more layer just to make things tidy in the same solution with 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.
So, now we have successfully added the EF references in the project. It has also added App.config and packages.config file just to make the proper configurations for EF in there.
Now, since all the configurations in place, i can go ahead and get started with the context class and inherit the same with DbContext class.
so, DbContext is a class which undersstands EF code first approach and in order to understand my model classes, i need to convert the same in DbSet. So, basically a DbSet of these model class will allow EF to do manage objects or to allow any kind of CRUD operation required in the application. In order to do that 1st i need to reference my model classes to DAL layer, so that same can be exposed.
Now, one important point i would like to point out here, in order to validate your data model, you must validate the same against the designer, whether the desired diagram is generating or not. In order to do that, 1st what you need to do is to import one tool from Extensions ad Updates option. you need to just type “Entity Framework Power Tools” as shown below and then install the same. after installation VS might ask you to restart the IDE just to make sure that tool will take effect.
As you see above in snapshot, I have already installed that tool. Now, in order to validate the data model what you need to do 1st make sure that your DAL layer is marked as Startup Project, just to avoid the connection string error. And then do the following as shown below.
Now, when you do the same it might throw error if any is present like if any class hasn’t been annotated with [Key] attribute because EF won’t understand which is the key in the class. And if everything goes well, it will generate the diagram as shown below.
so, this was the diagram which was supposed to come. This is fairly simple model based on the class relationship. you could see in the diagram that 1st two entities are having relationship and other two are independent, i made the same way just to keep the things simple.
Now, another important concept one should understand that code first doesn’t bother about the database until runtime. So, this happens in two step 1st is to locate the database and 2nd step is to create the database if required.
Now, let’s start doing demonstration with one little console app where in i’ll be exposing the context to walk through one of the tables and print the result like shown below.
Now, when i ran the app, you could 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.
So, it may happen that if you are going to run the app again it would throw you an exception reason being the default behavior restricts the user for database initialization to one time, however we can do override the same 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 initialization every time, we could use database migrations. so, i need to go into package manager console and from there i need to enable database migrations like shown below
so, now when migrations enabled, we need to specifically set the option which one am going to use for migrations out of 4 as listed below.
- CreateDatabaseIfNotExists –> This is the default one .
so, these are the four options, so am going to use the last one, because in this scope it suits me.
Now, next step is seeding the database. so, basically i can mock some data either manually by directly entering the data into tables or via code. so, when we go via code approach, we term this as seeding of database. so, for doing the same we’ll override the configuration Seed method by changing the commented part as shown below.
so, above in the screen shot, I have added two records via 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 real app.
Now, when i run my app and step through it, it should produce these two record set in the console screen as shown below.
Now, with this i would like to wrap this module. I have also attached the sample code for your reference. Till then stay tuned and Happy Coding.
Download Link :-SampleModel
5,182 total views, no views today