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
Let us explore what is inside this file. Right click the Model1.edmx file > Open With.. > XML (Text) Editor > OK.
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.
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.
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:
The most important part to observe is that the ‘NorthwindEntities’ is a partial class that inherits from ObjectContext.
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:
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.
Let’s see how the constructors are used at runtime. Go to the Program.cs file we created in our previous article.
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
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)
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.
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 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 eBook 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 .NET Standard and the upcoming C# 8.0 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!