English 中文(简体)
Entity Framework Tutorial

Entity Framework Resources

Selected Reading

Entity F - Model First Approach
  • 时间:2024-11-03

Entity Framework - Model First Approach


Previous Page Next Page  

In this chapter, let us learn how to create an entity data model in the designer using the workflow referred to as Model First.

    Model First is great for when you re starting a new project where the database doesn t even exist yet.

    The model is stored in an EDMX file and can be viewed and edited in the Entity Framework Designer.

    In Model First, you define your model in an Entity Framework designer then generate SQL, which will create database schema to match your model and then you execute the SQL to create the schema in your database.

    The classes that you interact with in your apppcation are automatically generated from the EDMX file.

Following is a simple example of creating a new console project using Model First approach.

Step 1 − Open Visual Studio and select File → New → Project

Console Project

Step 2 − Select Installed → Templates → Visual C# → Windows from left pane and then in middle pane, select Console Apppcation.

Step 3 − Enter EFModelFirstDemo in the Name field.

Step 4 − To create model, first right-cpck on your console project in solution explorer and select Add → New Items…

Model

The following dialog will open.

Add New

Step 5 − Select ADO.NET Entity Data Model from middle pane and enter name ModelFirstDemoDB in the Name field.

Step 6 − Cpck Add button which will launch the Entity Data Model Wizard dialog.

Model Wizard Dialog

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

Step 8 − Right-cpck on the design surface and select Properties. In the Properties window, change the Entity Container Name to ModelFirstDemoDBContext.

Design Surface

Step 9 − Right-cpck on the design surface and select Add New → Entity…

Add New Entity

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

Entity Dialog

Step 10 − Enter Student as entity name and Student Id as property name and cpck Ok.

Student

Step 11 − Right-cpck on the new entity on the design surface and select Add New → Scalar Property, enter Name as the name of the property.

New Entity

Step 12 − Enter FirstName and then add another two scalar properties such as LastName and EnrollmentDate.

Scalar Properties

Step 13 − Add two more Entities Course and Enrollment by following all the steps mentioned above and also add some Scalar properties as shown in the following steps.

Visual Designer

Step 14 − We have three entities in Visual Designer, let’s add some association or relationship between them.

Step 15 − Right-cpck on the design surface and select Add New → Association…

Add Association

Step 16 − Make one end of the relationship point to Student with a multippcity of one and the other end point to Enrollment with a multippcity of many.

Multippcity Of One

Step 17 − This means that a Student has many Enrollments and Enrollment belongs to one Student.

Step 18 − Ensure the Add foreign key properties to Post Entity box is checked and cpck OK.

Step 19 − Similarly, add one more association between Course and Enrollment.

Course And Enrollment

Step 20 − Your data model will look pke the following screen after adding associations between entities.

Data Model

We now 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.

Step 1 − Right-cpck on the design surface and select Generate Database from Model…

Database From Model

Step 2 − You can select existing database or create a new connection by cpcking on New Connection…

Generate Database

Step 3 − To create new Database, cpck on New Connection…

Connection Properties

Step 4 − Enter Server name and database name.

Server And Database

Step 5 − Cpck Next.

Server And Database 1

Step 6 − Cpck Finish. This will add *.edmx.sql file in the project. You can execute DDL scripts in Visual Studio by opening .sql file, then right-cpck and select Execute.

DDL Scripts

Step 7 − The following dialog will be displayed to connect to database.

Connect To Database

Step 8 − On successful execution, you will see the following message.

Successful Execution

Step 9 − Go to the server explorer, you will see that the database is created with three tables which are specified.

Database Created

Next, we need to swap our model to generate code that makes use of the DbContext API.

Step 1 − Right-cpck on an empty spot of your model in the EF Designer and select Add Code Generation Item…

EF Designer

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

Dialog Open

Step 2 − Select EF 6.x DbContext Generator in middle pane and enter ModelFirstDemoModel in Name field.

Step 3 − You will see in your solution explorer that ModelFirstDemoModel.Context.tt and ModelFirstDemoModel.tt templates are generated.

Template Generated

The ModelFirstDemoModel.Context generates the DbCcontext and the object sets that you can return and use for querying, say for context, Students and Courses etc.

The other template deals with all the types Student, Courses etc. Following is the Student class, which is generated automatically from the Entity Model.

CSharp Code

Following is the C# code in which some data are entered and retrieved from database.

using System;
using System.Linq;

namespace EFModelFirstDemo {

   class Program {

      static void Main(string[] args) {

         using (var db = new ModelFirstDemoDBContext()) {

            // Create and save a new Student

            Console.Write("Enter a name for a new Student: ");
            var firstName = Console.ReadLine();

            var student = new Student {
               StudentID = 1,
               FirstName = firstName
            };
				
            db.Students.Add(student);
            db.SaveChanges();
				
            var query = from b in db.Students
               orderby b.FirstName select b;

            Console.WriteLine("All student in the database:");

            foreach (var item in query) {
               Console.WriteLine(item.FirstName);
            }

            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
         }
      }
   }
}

When the above code is executed, you will receive the following output −

Enter a name for a new Student:
Ap Khan
All student in the database:
Ap Khan
Press any key to exit...

We recommend you to execute the above example in a step-by-step manner for better understanding.

Advertisements