Friday, August 22, 2014

Introduction to Entity Framework Code First

The first version of entity framework was released in DOT NET framework 3.5. Entity Framework has 3 different workflows(i.e. ways to create the model). These are: Code First, Database First, and Model First.

Entity Framework Code First was introduced in EF 4.1.

Code First allows you to create the model from your existing POCO(Plain Old CLR Objects) classes.

Developers don't need to wait till the database is ready to start coding. They can start coding by creating classes as their need which will be converted to tables later by Entity Framework. The conversion of classes to tables will vary depending upon the data annotation attributes assigned or mappings specified by FluentAPI.

Code First, Database First and Model First are only different ways to create model for data access. Once the models are created, Entity Framework runtime behaves the same regardless how you created the model.

The following diagram will help you to select the correct approach of creating model.



(Image source: Programming Entity Framework: Code First by Julia Lerman and Rowan Miller)

So if you want to create model from code(i.e from POCO classes) you can choose Code First irrespective of new or existing database.

If you want to create model from designer(i.e from EDMX file) you have two options: if new database then you can pick Model First else if existing database then Database First.

DbContext


DbContext is the light-weight version on Entity Framework's ObjectContext. DbContext is the core of Code First API.

Microsoft found some of the features of ObjectContext are not used by developers in their daily programming life. So Microsoft's Entity Framework team has simplified the ObjectContext to DbContext which contains the simple methods and properties.