- Entity F - Nested Entity Types
- Entity F - Multiple DbContext
- Entity F - Code First Migration
- Entity Framework - Seed Database
- Entity Framework - Fluent API
- Entity Framework - Data Annotations
- Entity Framework - First Example
- Entity F - Code First Approach
- Entity Framework - Colored Entities
- Entity Framework - Track Changes
- Entity Framework - Validation
- Entity Framework - Explicit Loading
- Entity Framework - Lazy Loading
- Entity Framework - Eager Loading
- Entity Framework - Migration
- Entity Framework - Inheritance
- Entity Framework - Spatial Data Type
- Entity F - Command Interception
- Entity F - Command Logging
- Entity F - Projection Queries
- Entity Framework - Persistence
- Entity F - Asynchronous Query
- Entity Framework - Enum Support
- Entity Framework - Native SQL
- Entity F - Table-Valued Function
- Entity F - Disconnected Entities
- Entity F - Stored Procedures
- Entity Framework - Index
- Entity Framework - Views
- Entity Framework - Transaction
- Entity Framework - Concurrency
- Entity F - Database Operations
- Entity Framework - DEV Approaches
- Entity F - Database First Approach
- Entity F - Model First Approach
- Entity F - Code First Approach
- Entity Framework - Lifecycle
- Entity Framework - Relationships
- Entity Framework - Types
- Entity Framework - DbContext
- Entity Framework - Data Model
- Entity Framework - Database Setup
- Entity F - Environment Setup
- Entity Framework - Architecture
- Entity Framework - Overview
- Entity Framework - Home
Entity Framework Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Entity Framework - Model First Approach
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
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…
The following dialog will open.
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.
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.
Step 9 − Right-cpck on the design surface and select Add New → Entity…
Add Entity dialog will open as shown in the following image.
Step 10 − Enter Student as entity name and Student Id as property name and cpck Ok.
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.
Step 12 − Enter FirstName and then add another two scalar properties such as LastName and EnrollmentDate.
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.
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…
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.
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.
Step 20 − Your data model will look pke the following screen after adding associations between entities.
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…
Step 2 − You can select existing database or create a new connection by cpcking on New Connection…
Step 3 − To create new Database, cpck on New Connection…
Step 4 − Enter Server name and database name.
Step 5 − Cpck Next.
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.
Step 7 − The following dialog will be displayed to connect to database.
Step 8 − On successful execution, you will see the following message.
Step 9 − Go to the server explorer, you will see that the database is created with three tables which are specified.
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…
You will see that the following Add New Item dialog opens.
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.
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.
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