Sunday, September 27, 2015

Different Approaches of Entity Framework



Entity Framework provides three different approaches to deal with the model, and each one has its own pros and cons. Ambily Kavumkal Kamalasanan discusses the advantages of the Model, Database, and Code First approaches to modelling in Entity Framework 5.0. Entity Framework still has its share of issues and is not widely accepted yet - but through contributing to its ongoing development the community can make it more stable and increase its adoption.

In this article I will be describing the three approaches to using Entity Framework (EF).
  1. Model First 
  2. Database First 
  3. Code First


I will illustrate how to use these techniques using Entity Framework 5.0, which has several performance improvements and new features which will be highlighted as part of the sample implementation. I will then go on to explain the relative advantages of each approach when designing the database.


Model First

In the Model First approach, the database model is created first using the ORM designer in Visual Studio. Once the model consisting of entities and relationships has been designed, the physical database will be generated from the model.

Walk through – Creation of Model First

In order to create the model, you should create an empty ASP.Net project in Visual Studio and add a new ADO.Net Entity Data Model, which for this example we’ll call ModelSample.

Figure 1: Add ADO.Net Entity Data Model

This will open the Entity Data Model Wizard. Select the Empty Model from the Model Contents selection.

Figure 2: Choose Model Contents

This loads the entity data model designer. Add Entities from the toolbox to our entity data model designer. Link the entities using the ‘Association from Toolbox to complete the model design.

Figure 3: Sample designer with entities

New feature: Entity Color. As you can see in the above diagram, we can color the entities appropriately for better understanding and grouping. In our sample, leave-related entities are colored with orange, organization details in purple and the employee details in blue.

Once the entity model design is completed, generate the database from the model using the ‘Generate Database from Model’ context menu. Right-click on the designer to invoke the Context menu, then select the ‘Generate Database from Modeloption.

Figure 4:Generate Database from Model

Select an existing database connection or create a new connection to create the sample database from the Model. For this sample, I have used SQLExpress with the SampleDB database connection.

Figure 5: Choose Data Connection

This will generate the DDL statements, and the generated script will be added to the solution as a script file.

Figure 6: Specify DDL file name

The script file generated in the previous step will be opened in Visual Studio. Click ‘Executein order to create the database using the generated script.

Figure 7: Execute Script

Now, the database with all tables and relationships is created in the database server. For working with the new database, generate the code using the Code Generation Strategy; set this value as “default”.

Figure 8: code Generation Strategy

This will generate the entity framework code and database context classes corresponding to the defined model. We can use these new classes from the business layer to perform various database operations. Verify the code generated under the Modelname.Designer.cs file.


Figure 9: Designer Code

We can sync the Model with the database either way using the context menu options – ‘Generate Database from Model’ or ‘Update Model from Database’. You can modify the model and then invoke the ‘Generate database from Model context menu option to update the database schema. Any modification in database schema can get updated to the model using the ‘Update Model from Database’ context menu option.

New feature: Multiple-diagrams per single Model.
Another new feature introduced in EF 5.0 is to allow the use of multiple diagrams for a single model. We can move selected entities to another diagram in order to reduce the complexity of the main diagram. Select the entities by holding shift key and select the “Move to new diagram” option from the context menu.

Figure 10: Move to new diagram

Let us move the entities related to leave to another diagram. This will create a new diagram with selected entities; in our case Leave and Leavedetail.

Figure 11: Multiple diagram for single Model

As you can see, the relationship between the LeaveDetail entity and the Employee entity has been removed. We can use the new ORM feature to include the related entities in the second diagram by keeping one copy of the same in the first diagram for better readability. We can include the related entities in the second diagram using “Include Related” option. This will create a copy of all the related entities in the second diagram. Select the Leavedetail entity, right-click and select the option “Include Related” to include the employee entities in the second diagram.


Figure 12: Include Related

Figure 13: Multi-diagram with Include Related

Database First

The next approach supported by the Entity Framework is the database-first approach. In the database first approach, we are creating the entity framework from an existing database. We use all other functionality, such as the model/database sync and the code generation, in the same way we used them in the Model First approach.
Create the ADO.Net Entity Data model using the ‘Generate from Database’ option.

Figure 14: Choose Model Content

Select an existing connection or new connection from the ‘choose data connection window. We are using thesampleDB that we created as part of our Model First sample. Now, select the database objects suitable for your project such as Tables, Views and Stored procedures, functions from the ‘Choose your Database Objects’ window.

Figure 15: Choose database objects

This will generate the designer with selected entities and associations as shown below.

Figure 16: Entity data model designer

Create the code using the ‘Code Generation Strategy property, and perform the sync between the database and model in the same way that the Model-first approach works. Any sync back to the database will recreate the database and the existing data will be lost.

New feature: There is now support for Table-valued functions. Before using the SampleDB in the database-first approach, we have added a Table-valued function called UpdateLeave to the database. You’ll notice that the new Table-valued function is added under the Complex Type region inside the Designer.cs file. Support for the Table-valued function has been added as part of Entity Framework 5.0 and is available for the database-first approach only.
New feature: Enum properties. Support for enum properties are added as part of Entity Framework 5.0. Add one Integer property, say Relationship to the entity. Right-click on the property and select the “Convert to Enum” option from the context menu.

Figure 17: Convert to Enum

Add the enumeration members and values in the ‘Add Enum Type window.

Figure 18: Add Enum Type

Instead of adding each value, we can refer an external type using the ‘Reference external type option.
Here is the generated code for the new Enum added inside the Designer.cs file

[EdmEnumTypeAttribute(NamespaceName="SampleDBModel", Name="Relationship")]
   [DataContractAttribute()]
   public enum Relationship : int
   {
      ///<summary>
      ///No Metadata Documentation available.
      ///</summary>
      [EnumMemberAttribute()]
      Mother=1,
 
      ///<summary>
      ///No Metadata Documentation available.
      ///</summary>
      [EnumMemberAttribute()]
      Father=2,
 
      ///<summary>
      ///No Metadata Documentation available.
      ///</summary>
      [EnumMemberAttribute()]
      Spouse=3,
 
      ///<summary>
      ///No Metadat aDocumentation available.
      ///</summary>
      [EnumMemberAttribute()]
      Child=4
   }

New feature: Support for Geography and Geometry types. Support for the DBGeography and DBGeometry types are added as part of Entity Framework 5.0.

Figure 19: Geometry & Geography supports