Identifying Entity Framework Development Approaches

Introduction

 
The Entity Framework provides three approaches to create an entity model and each one has their own pros and cons.
  1. Database First
  2. Model First
  3. Code First

Database First

 
The Database First approach enables us to create an entity model from the existing database. This approach helps us to reduce the amount of code that we need to write. The following procedure will create an entity model using the Database First approach.
 
Step 1
 
Create the ADO.Net entity data model using the "Generate from Database" option.
 
 
Step 2
 
Select an existing connection or create new connection from "Choose Your Data Connection" windows and after this select database object (such as table, view and Stored Procedure) that are required into the project.
 
 
This will generate with selected entities and association (relationship among entities).
 
 
To update the model (in case of a database change), right-click on the model and select the “Update Model from Database” option and follow from Step 2.
 
 
Advantages
  • This approach is very popular when we have an existing database
  • The EDM wizard creates the entities and their relationships automatically
  • Extensibility is possible using a partial class or T4 templates
  • We need to write less code and put less effort into creating the entity model
  • Easy update if any changes are made to the database
Disadvantages
  • Very difficult to maintain a complex model
  • Model customization is very difficult. In other words, if we don't have a foreign key in the database and we need an association in the conceptual layer then we must create it manually and it is very difficult to maintain when we update the model from the database.

Model First

 
In this approach, model classes and their relation is created first using the ORM designer and the physical database will be generated using this model. The Model First approach means we create a diagram of the entity and relation that will be converted automatically into a code model.
 
The following procedure will create an entity model using the Model First approach.
 
Step 1
 
Create the ADO.net entity data model using the "Empty EF Designer Model" option.
 
 
Step 2
 
Now create the entity. Step 1 created the empty entity model. To add a new entity just right-click on the diagram and select “Add new” and the entity option. Fill in the entity name and database table name and primary key information.
 
 
Step 3
 
Now to add properties to the entity.
 
 
Step 4
 
Add associations (relation among entities) if any.
 
 
Step 5
 
Once the entity model design is completed, we can generate the database from this model using the "Generate Database from model" context menu option. Here we can select any existing database connection or create a new database connection to create the database from a model.
 
 
Step 5 will generate the DDL script and this generated file will be added to the solution as a script file.
 
 
 
Advantages
  • Visual designer to create a database schema
  • Model diagram can be easily updated when the database changes
  • Entity Framework generates the Code and database script
  • Extensibility is possible using a partial class
Disadvantages
  • When we change the model and generate SQL to sync the database then this will always result in data loss because the tables are dropped first.
  • We don't have much control on entities and database.
  • Requires a good knowledge of Entity Framework to update the model and database

Code First

 
The Code First approach enables us to create a model and their relation using classes and then create the database from these classes. It enables us to work with the Entity Framework in an object-oriented manner. Here we need not worry about the database structure.
 
As said earlier, we need to create a class that represents the database table. As an example I have created the two classes Employee and EmployeeDetails.
  1. public partial class Employee  
  2. {  
  3.     public int EmployeeId { get; set; }  
  4.   
  5.     [StringLength(10)]  
  6.     public string Code { get; set; }  
  7.   
  8.     [StringLength(50)]  
  9.     public string Name { get; set; }  
  10.   
  11.     public virtual EmployeeDetail EmployeeDetail { get; set; }  
  12. }  
  13.   
  14. public partial class EmployeeDetail  
  15. {  
  16.     [Key]  
  17.     [DatabaseGenerated(DatabaseGeneratedOption.None)]  
  18.     public int EmployeeId { get; set; }  
  19.   
  20.     [StringLength(25)]  
  21.     public string PhoneNumber { get; set; }  
  22.   
  23.     [StringLength(255)]  
  24.     public string EmailAddress { get; set; }  
  25.   
  26.     public virtual Employee Employee { get; set; }  
  27. }  
The next step is to create a DbContext class and define a DbSet properties type of entity classes that are represented as a table in the database.
  1. public partial class CodeFirst : DbContext  
  2. {  
  3.     public CodeFirst() : base("name=CodeFirst")  
  4.     {  
  5.     }  
  6.   
  7.     public virtual DbSet<Employee> Employees { get; set; }  
  8.     public virtual DbSet<EmployeeDetail> EmployeeDetails { get; set; }  
  9.   
  10.     protected override void OnModelCreating(DbModelBuilder modelBuilder)  
  11.     {  
  12.     }  
  13. }  
Now if we want to create the database from the model then open the Package Manager Console and follow the migration procedure as shown below.
 
 
Step A: Enable Migration
 
enable-migrations -ContextTypeName “Conext class type with namespace” -MigrationsDirectory:”Migration directory”
 
Example
 
PM> enable-migrations -ContextTypeName
 
EntityFrameworkApproaches.CodeFirst.CodeFirst -MigrationsDirectory:CodeFirst
 
 
Step B: Add Migration
 
Add-Migration -configuration –DbContext –Migrations –Configuration “Class-with-Namespaces” -Migrations- “Name”
 
Example
 
PM> Add-Migration -configuration EntityFrameworkApproaches.CodeFirst.Configuration InitialEntities
 
 
Step C: Update database
 
Update-Database -configuration –DbContext – Migrations “Configuration Class withNamespaces” –Verbose
 
Example
 
PM> Update-Database -configuration:EntityFrameworkApproaches.CodeFirst.Configuration -Verbose
 
 
Advantages
  • There is full control of the model from the code. There is no EDMX/designer and no auto-generated code
  • It supports database migrations, so it is very easy to sync various databases
  • We have more customization options and more control
  • We can also use Code First to map our model to an existing database; to learn more click here
Disadvantages
  • It is very difficult to maintain a database compared to a visual design tool
  • Requires a good knowledge of C# and data annotation
Comparing Approaches
 
Feature Entity Framework Approaches
Code First Model First Database First
Support ORM designer tool (visual creation of data model)
No.
No EDMX support hence there are no any support of visual creation ofdata model.
Yes.
Yes.
Generates code and database scripts
Yes.
Yes.
NA
In this approach, we already have database and from the database wecreate model.
Extensible through partial classes
NA
In this approach, all are POCO classes,
Yes.
Yes.
Full control over model from code
Yes.
No.
No.
Manual changes to the database are possible?
Yes.
Yes.
Yes.
Easy to modify the model?
Yes.
Yes.
Yes.
An existing database can be used?
Yes.
To know more click here.
NA
Yes.
 
Selecting Right Approach
 
Definitely the development approach depends upon the project situation. The following diagram may help us to select the correct approach for your project. As in this diagram, if we already have domain classes, the Code First approach is best suited for our application. The same as if we have a database, Database First is a good option. If we don't have model classes and a database and require a visual entity designer tool then Model First is best suited.
 
 
My opinion
 
It definitely depends on the situation what approach is more suitable for a project / application but after comparing three approaches, I still prefer Code First approaches. I have a couple of reasons for that.
  • Code First supports database migrations.
  • Much simpler to synchronize databases among developers and different versions of the application.
  • More control over the Model. In other words, we have more control over how the entities and associations are created and how they work.

Summary

 
Entity Framework provides three approaches to create and maintain entity models. Each one has their own pros and cons. Depending upon the situation, we can select one of the best suited approaches for our application.
 
I hope this helps!


Similar Articles