Modelling Approaches for Entity Framework: Database First, Model First, Code First
While working with ADO.NET Entity Framework, you have 3 types of modelling approaches which are:
1. Database First
2. Model First
3. Code First
Lets discuss these Entity Framework modelling approaches in detail.
1. Database First Modelling Approach
When you generate EDMX from existing database, then it is a Database First approach. So in Database First approach, when you add ADO.NET Entity Data Model, you should select ‘Generate from database’ instead of ‘Empty Model’.
2. Model First Modelling Approach
In Model First approach, you create Entities, Relationships, and Inheritance hierarchies directly on the design surface of EDMX. So in Model First approach, when you add ADO.NET Entity Data Model, you should select ‘Empty Model’ instead of ‘Generate from database’.
After creating required entities, associations and inheritance on design surface of the empty model, you can use designer’s context menu option ‘Generate database from model’. It will not generate new database from model. It will only give you DDL to execute in existing database and it is up to you to execute this DDL.
3. Code First Modelling Approach
In Code First approach, you avoid working with visual model designer (EDMX) completely. You write your POCO classes first and then create database from these POCO classes. Developers who follow the path of Domain-Driven Design (DDD) principles, prefer to begin by coding their classes first and then generating the database required to persist their data.
DbContext and DbSet: There are two new types introduced for Code First approach, DbContext and DbSet. DbContext is a simplified alternative to ObjectContext and is the primary object for interacting with a database using a specific model. DbSet is a simplified alternative to ObjectSet and is used to perform CRUD operations against a specific type from the model in Code First approach.