Exploring how the Entity Data Model (EDM) Generates Code and Executes Queries – Entity Framework 4.0

Posted by: Suprotim Agarwal , on 11/9/2010, in Category Entity Framework
Views: 118727
Abstract: In this article, I will explain what happens behind the scenes in the Entity Data Model and also looks at the files responsible to generate the code and execute queries on your behalf.

In my previous article Create an Entity Data Model From a Database – Entity Framework 4.0 we created our first application using Entity Framework 4.0 and Visual Studio 2010. We saw how to create an Entity Data Model and also query it. In this article, I will explain how the Entity Data Model works and the files responsible to generate the code and execute queries on your behalf.

Assuming you have downloaded the code in my previous article, open your Solution Explorer and look out for a file called Model1.edmx. This file is an XML file that defines the schema for your data model. You will also find a file called Model1.Designer.cs. This file contains the mapping objects for your data model.

Exploring the EDMX file

The designer view of the .edmx file is shown below, with a Customer and Order Entity that we created in our previous article

EDM Designer
 
Let us explore what is inside this file. Right click the Model1.edmx file > Open With.. > XML (Text) Editor > OK.

EDM Text Editor

 
Once you open Model1.edmx in the XML Editor, pay attention to the 3 main sections in the file: SSDL, CSDL and C-S mapping.

 Model1.edmx

We know that Entity Framework maps database tables to objects. This is done in 3 different layers:

Logical Layer: The Logical Layer also called Storage Layer is defined by the Store Schema Definition Language (SSDL) and defines the structure of the tables and relations between them.

Conceptual Layer: The Conceptual Layer is defined by the Conceptual Schema Definition Language (CSDL) and defined .NET classes.

Mapping Layer: The Mapping Layer is defined by Mapping Specification Language (MSL) and connects the entity type definition from the CSDL to the metadata defined in the SSDL, hence the name C-S mapping. So the mapping is essentially from .NET classes to the table structure and its relations.

At runtime, this .edmx is split into these three different files (.ssdl, .csdl and .msl). Feel free to explore the different layers and study the mappings to understand them better.


EDMX Composition 

Exploring the Model1.Designer.cs file

The Model1.designer.cs file gets auto-generated by the EntityModelCodeGenerator tool, while creating your Entity Data Model (EDM) through the wizard. This file contains the contexts and entities that are used by the EDM. The structure of this file is as shown below:


Model1.Designer Structure 

The most important part to observe is that the ‘NorthwindEntities’ is a partial class that inherits from ObjectContext.

Object Context

The ObjectContext class provides facilities for querying and working with entity data as objects, keeping track of the entity objects, along with the state information (added, modified, deleted) and the ability to update entities and write changes back to the database.

Since the NorthwindEntities derives from ObjectContext, it contains the properties for every table included in your data model. Each property is a strongly typed ObjectSet (we will come to ObjectSet shortly) as shown below:


Image5 

Exploring the Program.cs code

If you look at the NorthwindEntities class, you will see it has constructors that let you connect to the database from which the model was generated.


Image6 

Let’s see how the constructors are used at runtime. Go to the Program.cs file we created in our previous article.

Image7

You will observe that we are using the query-expression syntax to write LINQ queries.

The code starts with the line

using(var context = new NorthwindEntities()

What we are doing here is creating a new instance of the ObjectContext and implicitly establishing a connection to the database (using the constructors of the NorthwindEntities). Observe the code is wrapped in a using() block. This is a good programming practice as when the execution leaves the using block, a call is made to the Dispose() method on the ObjectContext, which closes any active database connections and does critical resource cleaning for us.

Add a breakpoint after the foreach loop and debug the code to understand the rest of the code better.

The next line of code is as follows:

var custWithOrders = context.Orders
    .Where(o => o.OrderDate > new DateTime(1998, 1, 1));

With the code running in Debug mode, hover your mouse over context.Orders

Image8

We see that when we request for the EntitySet ‘Orders’, EF returns a System.Data.Objects.ObjectSet of ‘Orders’ type and uses the Orders navigation property to query all the Orders whose OrderDate is after 1st January, 1998.

Note: An ObjectSet represents a typed entity set that is used to perform create, read, update, and delete operations. ‘ObjectSet’ derives from another class called ‘ObjectQuery’ which we will see shortly.

 The next piece of our code is a for-each loop

foreach (var cust in custWithOrders)
{
}

If you place your cursor at the custWithOrders variable, you will see that the type is a System.Data.Objects.ObjectQuery, that ‘ObjectSet’ derived from)


Image9

It is this ObjectQuery class that is used to construct queries and execute them. In return we get objects against which we can perform actions like adding new objects or deleting existing ones. Once the ObjectQuery gets executed, we get the Orders results which also contains relationship to the Customer table.

Finally, we use the cust variable to access the properties of the Orders and Customer table and write it to the console.

Note: The System.Data.Objects namespace is an important namespace with a number of classes that provides querying functionality for EF.

If you are wondering where did we use the different layers of .edmx file we discussed earlier, then keep in mind that the ObjectContext class is generated, by reading the conceptual layer of the model.

I hope we are making some progress here and you are able to relate the different pieces of EntityFramework and how they work together.

Hope you liked the article and I thank you for viewing it.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by George on Tuesday, November 9, 2010 8:22 AM
Thanks for the article. Learning a lot.
Comment posted by Deepak Mohnot on Sunday, November 14, 2010 1:25 AM
Thanks for sharing this article.Waiting eagerly for next upcoming series on EF..
Comment posted by Mostafa on Tuesday, February 15, 2011 2:35 PM
Thank you , That was so informative to me . I'm going to read all your EF4 articles .
Comment posted by DharmaRao on Thursday, June 7, 2012 1:15 AM
Explaination is easy to understand. I could gain the knowledge about EF very well
Comment posted by Mo on Thursday, October 11, 2012 7:27 AM
Can you please include a VB version of this tutorial?
Comment posted by Gaurav Verma on Wednesday, January 23, 2013 8:24 AM
Nice description, helped me a lot, Thanks for this.
Comment posted by Vaibhav on Monday, February 4, 2013 6:16 AM
The underlying provider failed on Open. at

foreach (var cust in custWithOrders)
                {
                 Console.WriteLine("{0} from  {1} Ordered Item on {2}",
                        cust.Customer.CustomerID,
                        cust.Customer.CompanyName,
                        cust.OrderDate
                        );
                }
Comment posted by Srinivas on Wednesday, April 9, 2014 2:03 AM
A good article for beginners on EF.