This tutorial introduces the new functionalities that were added to Entity Framework 4.1. It shows the differences between the approaches and acts as an introduction to these new features.
Database First & Model First
The Database First approach is interesting when the database already exists. You use Visual Studio and the Entity Framework Designer to generate the C# and VB.NET classes which reflect the existing database model.
You may then change relations and structures using the Designer (or the XML mapping files) to further optimize the model. The priority is the database - the code and the model are only secondary.
The Model First approach is important when you begin from scratch. You start with the entity model and use the Entity Framework Designer to design the relations and the entities.
Then you generate the C# and VB.NET classes and also the database from within Visual Studio. The priority is the model - the code and the database are only secondary.
Code First
When your priority is the code and you want to begin from scratch without any existing schemas or XML mapping files using source code, then the approach is called Code First.
You simply create your domain classes and Entity Framework 4.1 will easily allow to use them with the database and the future model.
You use a context and are able to execute Linq2Entities queries in no time ! You may even take advantage of the change tracking features !
Entity Framework handles all of the background work and manages the interaction with the database. All the classes that are used during runtime are auto-generated.
In this case the configuration is not read from XML files but instead read from the configuration of the DbContext object in memory.
Code First allows:
- Developing without the need to use the Designer or XML mapping files
- Defining the objects of the model based on a POCO (Plain Old CLR Objects) approach
Explanation:
- Design and implement a company domain with Managers, Collaborators and Departments.
- Create your classes using a standard object oriented approach and using inheritance when appropriate.
- Use the POCO approach for your classes where possible.
- Note that for being able to use the auto-mapping feature for the primary keys you need to have named your class properties like this : [Classname]Id.
- Entity Framework 4.1 allows connecting those POCO classes with the database very easily by using the ObjectContext class (and in particular the DbContext class).
- The last step consists of defining the connection to the database within the web.config or app.config files. Note that EF will search for the connection string that has the same name as the class that was inherited from the DbContext class. You may however define a different name ("CompanyContext" in our example).
[Tutorial] Code First with Entity Framework 4.1
Part1: Introduction to the Code First approach