In the Model-First approach, you create the entities, relationships, and inheritance hierarchies directly on the design surface of EDMX and then generate the database from your model.
First of all, add the new Entity Data Model by right clicking on the project in the solution explorer in Visual Studio (2012/2015/2017) -> Add -> New Item. This will open the Add New Item popup. In the popup, select ADO.NET Entity Data Model, provide an appropriate name to an EDM and click the Add button. This will open the Entity Data Model Wizard. Select Empty EF Designer model and click Finish in the wizard, as shown below.
You can create an entity, association and inheritance on an empty designer by right clicking on designer surface -> Add New -> Entity.
In the Add Entity dialogue, enter the name of the entity. Also, you can change the default settings for the Entity set and key property. We will keep the default settings. Click OK to generate an entity.
You can also add properties in the generated entity by right clicking on the entity – > Add New -> Scalar Property.
Enter the name of the scalar property as shown below.
In the same way, you can add other entities and associations using the toolbox.
After creating the required entities, associations, and inheritance on the design surface of the empty model, you can use the designer’s context menu option ‘Generate database from model’ to generate the DDL script.
This will open the Generate Database Wizard. You can select the existing database or create a new connection by clicking on New Connection... Select database server, enter the name of the database to create and then click OK. It will ask you for the confirmation for creating a new database. Click Yes to create a database.
Click Next to generate the DDL for the DB model as shown below.
This will add the
<ModelName>.edmx.sql file in the project. You can execute DDL scripts in Visual Studio by opening the .sql file -> right click -> Execute.
Now, you can generate the context class and entities by right clicking on the designer and selecting Add Code Generation Item... This will open a popup to select the EF 6 or EF 5 DbContext Generator item. Select the EF 6 DbContext Generator item as we are using EF 6 and click the Add button.
This will add the
<ModelName>.tt with the context class and entity classes as shown below.
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.