Contexts and Entities in EDMX File in Entity Framework

Contexts and Entities in EDMX File in Entity Framework

Contexts and Entities in EDMX play a vital role and you must understand the purpose of these. Context contains all the logic for interacting with database and Entities represent database tables. Entites region contain public partial classes and public properties. Lets discuss it in detail:

When you create any EDMX file, follwing files are generated with it.

Model1.edmx
Model1.tt
Model1.Context.tt
Model1.Designer.cs
Model1.edxm.diagram
Model1.Designer.cs

Automatic code is generated in this file which contains context and entities if the "Code Genereation Strategy" is set to Default from None.

Also some points to note for this file

1. Manual changes to this file may cause unexpected behavior in your application.
2. Manual changes to this file will be overwritten if the code is regenerated.


Contexts and Entities in Model1.designer.cs

ObjectContext

If you open Model1.designer.cs, you can see two main regions, Contexts and Entities. expand contexts region. You can see partial class with suffix ‘entities’ and derived from ObjectContext class.

This class represents EntityContainer which you can see from XML view of Model1.edmx or from EDM property window. You can call this as context class.

This class is the primary class for interacting with entity objects and database. An instance of the ObjectContext class encapsulates the connection to the database, metadata that describes the model, and an ObjectStateManager object that tracks objects during create, update, and delete operations.

ObjectSet

Each EntitySet in context class is a type of ObjectSet<> that wraps the entity. e.g. ObjectSet.

EntityType

If you expand ‘Entities’ region, you can see many partial classes that are derived from EntityObject. This classes are EntityTypes of you model.

EntityType is a datatype in the model. You can see each EntityType for your conceptual model in XML. If you expand EntityType node in XML, you can see each properties and its type and other info.

EntityContainer

EntityContainer is a wrapper for EntitySets and AssociationSets. It is critical entry point for querying the model.

EntitySet

EntitySet is a container for EntityType. It is set of same entitytype. You can think it like db table.

AssociationSet

AssociationSet defines the relation between each EntitySet.

Model1.Context.tt is a context template file and Model1.tt is entities template file. 

Model1.tt and Model1.Context.tt templates, generate model entities and context. 

Model1.Context.tt: It produces a strongly typed ObjectContext for the Model1.edmx

Model1.tt: It is responsible for generating a file for each EntityType and ComplexType in the Model1.Context.tt.