Entity Framework - Model First Approach

Entity Framework supports the three approaches given below
  1. Schema First approach.
  2. Model First approach.
  3. Code First approach.
In the Model First approach, you create Entities, relationships, and inheritance hierarchies directly on the design surface of EDMX and then generate database from your model. 
 
Now, let's create a simple Windows Forms application using Model First approach.
Then, add ADO.NET Entity Data Model, as shown below.


 Select Empty EF Designer model and click Next button. The Entity Framework Designer opens with a blank model. Now we can start adding entities, properties and associations to the model.


Right-click on the design surface and select Add New → Entity



Add Entity dialog will open as shown in the following image.


Enter Employee as entity name and Id as property name and click Ok. Then, Right-click on the new entity on the design surface and select Add New → Scalar Property, enter Name as the name of the property. then add another scalar property 'Address'.
Add another entity 'Department' by following same previous steps.
Now add association, Right-click on the design surface and select Add New → Association




The data model will look like following after adding association between entities.


Now we have a simple model that we can generate a database from and use to read and write data. Let's go ahead and generate the database.
Right-click on the design surface and select Generate Database from Model


Select the database and click Next


Click Finish. This will add *.edmx.sql file in the project. You can execute DDL scripts in Visual Studio by opening .sql file, then click Execute.





The following dialog will be displayed to connect to database.


As you can see from the output, it failed to execute our SQL script.

This because the object Department and Employee already exists in our underlying database, so delete those objects from the database.





After deleting Department and Employee from database and executing the script, we should not get any error.




Go to the server explorer, you will see that the database is created with two tables which are specified.


Next, we need to swap our model to generate code that makes use of the DbContext API.
Right-click on an empty spot of your model in the EF Designer and select Add Code Generation Item.


You will see that the following Add New Item dialog opens.




Select EF 6.x DbContext Generator in middle pane and enter ModelFirstModel in Name field.
You will see in your solution explorer that ModelFirstModel.Context.tt and ModelFirstModel.tt templates are generated.





So, in this way, you can design your DB model and then generate a database and classes based on the model. This is called the Model-First approach.
Entity Framework - Model First Approach Entity Framework - Model First Approach Reviewed by Bloggeur DZ on 03:23 Rating: 5

Aucun commentaire:

Fourni par Blogger.