Creating Model Using Database-First Approach

The following walkthrough describes how to generate an Entity Framework model from the existing database, manually add and edit classes and components and generate C# code for the model.

We shall use the standard Northwind database. For more information on how to download and install this database, see here.

ExpandedToggleIcon        Prerequisites

In order to complete this walkthrough, you will need access to the database server you are using. You will also need a data provider to the corresponding server installed on your system. The Northwind database must be created on the server. In Microsoft Visual Studio, you should create a new project that will be used for the purpose of this walkthrough.

ExpandedToggleIcon        Creating a Model from the Existing Database

To create a model from your existing database, perform the following sequence of actions:

1.In the Solution Explorer window, right-click the name of your project.
2.From the shortcut menu, select the Add command and select the New Item option.

note Note

In the standalone application click the Create New Model button on the Entity Developer toolbar.

Images_T_EF_DBF_AddNewItem

3.In the Installed Templates column of the Add New Item window, select Data.
4.In the central column of the Add New Item window, select Devart Entity Model.

note Note

In the standalone application in the displayed New Model dialog select Devart Entity Model and click Create.

5.Click Add.

Images_T_EF_DBF_CMW1

6.Select the Database First option and click Next.

Images_T_EF_DBF_CMW2

note Note

This page may differ from the one pictured above, depending on which provider is selected.

7.On the Set up connection properties page, specify connection parameters as appropriate for the type of the server to be used.
8.(Optional) To check that the connection is valid, click Test connection. If the connection cannot be established, correct the entered data and repeat this step.
9.Click Next.

Images_CreateNewModel3

10.  On this page, select the Generate From Database option and click Next.

Images_CreateNewModel4

11.  On the Select database objects page, select the table and/or views as well as stored procedures and functions that are to be included in the model and click Next.

Images_CreateNewModel5

12.  On the Set up naming rules page, define the naming rules for your model and click Next.

Images_T_EF_DBF_CMW_Model_Properties

13.  On the Model properties page, specify the properties of the model:

Use the Enter the namespace for model objects field to define the namespace where model objects will be placed in when generating code.

Use the Enter the name of the entity container field to specify the name of the entity container to contain all instances of entities for the Entity Data Model; you can easily change it later.

In the Entity Framework version drop-down list specify the version of Entity Framework that will be used for your project. One of the following versions can be selected (depending on Entity Framework installed on your computer): 3.5, 4.x, 5 and 6.

Keep the Include foreign key columns into the model check box selected to include foreign key columns in the model (not available for Entity Framework v1).

Keep the Import selected stored procedures into the context model check box to create corresponding methods in the conceptual model for procedures and functions selected at the stage of choosing model diagram contents. For functions and stored procedures that return one or more result sets, this will create complex types that correspond to the structure of the result.

Keep the Detect function-based column default value check box selected if you want columns having a function-based default value to be interpreted as Identity.

Keep the Preserve schema name in storage check box selected to indicate that schema name should be preserved in the storage part.

Keep the Detect Many-to-Many associations check box selected to indicate that many-to-many associations should be detected. If this check box is not selected, a class with two one-to-many associations will be generated for an intermediate table instead of a many-to-many association.

Keep the Detect Table Per Type inheritances check box selected to indicate that table per type inheritances should be detected.

Keep the Use database comments check box selected to indicate that comments for database objects, if supported by DBMS, should be used for model objects Documentation initialization and taken into account when executing model or database update operations.

Use the Save connection settings in App.Config (Web.Config) as option to specify that the connection string should be saved in App.Config (or Web.Config) with a certain name. If the check box is deselected, the connection string is specified explicitly in the model class constructor.

14.  Click Next.

Images_CreateNewModel7

15.  On the Choose Model Diagram Contents page, select, which entities should be displayed on the diagram. There are three options: All Entities (all entities are displayed on the diagram), Split by Schemas (entities of a schema are displayed on a separate diagram), or Custom (manually select the required entities).
16.  Click Next.

Images_T_EF_DBF_CMW_Choose_Template

17.  The Choose Code Generation page allows you to select code generation templates you want to add to the new model. By default this page contains the most frequently used template; the properties area of this page allows you to configure the properties of the selected template. Three buttons at the top of this page allow you to add more templates from gallery, add existing templates from disk and remove templates from the list.
 
Often users add the DbContext template and remove the EntityObject template on this page.
18.  Click the Add template button.

Images_Add_Template

19.  The Add Template dialog box lists all predefined and shared templates. Choose the required one and click OK. The selected template will be added to the list on the Choose Code Generation page together with all related templates (without which the template would work incorrectly).
20.  After all the required templates are added to the list on the Choose Code Generation page of the wizard, click Next.  
21.  The final page of the wizard is displayed. This page may differ depending on the options selected in previous steps. The download 'Entity Framework' NuGet package check box is displayed, if Entity Framework 4.x or 5 is selected and the list of code generation templates contains the DbContext template, or if Entity Framework 6 is selected (irrespective of the selected templates).

note Note

Absence of the Entity Framework NuGet package on your machine will prevent certain functionality from working properly.

22.  Click Finish.

The model is successfully created:

Images_T_EF_DBF_ModelCreated

ExpandedToggleIcon        Mapping Specifics in Entity Framework

In Entity Framework, a model consists of two main parts: a conceptual part (within the red rectangle on the screenshot below) and a storage part (within the green rectangle on the screenshot below).

Images_Model_parts

The conceptual part contains all of the model entities, whereas the storage part corresponds to the physical tables in the database. Model entities in the conceptual part are mapped to the objects contained in the storage part as described below.

To add or to edit mapping, perform the following sequence of actions:

1.In the conceptual part of the model within the Model Explorer window, right-click the entity, whose mapping should be defined or changed.
2.On the shortcut menu, select Mapping Details.

The Entity Mapping Details window is displayed:

Images_EntityMappingDetails_T_EF

3.(Optional) In the Storage Entities area, select the appropriate storage entity. To map the class to more than one storage entity, click Add a Table or View and specify another storage entity.
4.(Optional) In the Column Mapping area, enter or edit the parameters of column mapping.
5.(Optional) In the Conditions area, define one or more conditions for the columns.
6.Click OK.

Note that it is also possible to map the class to a query rather than a storage entity. For that purpose, navigate to the Query View tab and enter your query into the Query field and click OK. (Queries are written in Extended Structured Query Language (ESQL))

Another way to create storage part and mapping manually is using the Create Storage and Mapping option of the class, property and association context menus. If this option is selected for an object already having a Storage counterpart and mapping, a dialog box will be displayed offering to create the Storage object and mapping anew.

 

ExpandedToggleIcon        Code Generation Setup

This section explains how to set up code generation in Entity Framework models.

For the purpose of code generation, you may need to create and define folders, into which generated code will be saved, as well as other parameters available in the Properties window of the selected template.

The definition of output folders for code generation is optional, if such folders are of no importance for you, go directly to Step 8 of the procedure.

To define folders for code generation, perform the following sequence of actions:

1.In your project in the Solution Explorer window, create a folder for entities (for example, Entities) and a folder for the context (for example, Context).
2.Navigate to the Model Explorer window, select the template and click to display the Properties window for the selected template.

Images_T_EF_DBF_Properties

3.In the Output section of the model properties, click the Context Output line and then click the displayed three-dotted button.
4.In the Select Project Folder dialog box, select the appropriate folder for the context class file (for example, the Context folder that was created in Step 1 of this procedure) and click OK.
5.Click in the Entities Output line and click the three-dotted line to open the Select Project Folder window.
6.In the Select Project Folder window, select the appropriate folder for entity files (for example, the Entities folder that was created in Step 1 of this procedure) and click OK.
7.Select an appropriate value for the File Per Class property: if different folders are specified for the context and entities, the File Per Class parameter must be set to True.
8.Set the Generate Partial Class property to True define that for each class of the model a partial class should be generated, in which it will be possible to add code that won't be overwritten by the designer. The property can be used, if File Per Class is set to True.
9.To enable the entity property validation mechanism in the Validation section locate the Validation Framework row and select the appropriate framework; use the Validation Error Messages row to apply error messages stored in the application resources. For details on validation refer to Entity Property Validation.
10. To generate code, save the model in Microsoft Visual Studio. In the Entity Developer stand-alone application, click the Images_GenerateButton button on the toolbar or press F7.

Entities and context files are successfully generated and stored in the specified folders:

Images_T_EF_DBF_Mapping_Generated

This completes the procedure for creating an Entity Framework model from the existing database.

 

ExpandedToggleIcon        See Also


Send feedback on this topic

© 2008 - 2024 Devart. All rights reserved.