Entity Framework relies on the conceptual data model for all its working. Let's try to understand what the Entity Data Model (EDM) is and how Entity Framework uses it to manage the database operations.
The conceptual data model is the heart of Entity Framework. To use Entity Framework, we have to create the conceptual data model, that is, the EDM. The EDM defines our conceptual model classes, the relationships between those classes, and the mapping of those models to the database schema.
Once our EDM is created, we can perform all the CRUD operations (create, retrieve, update, and delete) on our conceptual model, and Entity Framework will translate all these object queries to database queries (SQL). Once these queries are executed, the results will again be converted to conceptual model object instances by Entity Framework. Entity Framework will use the mapping information stored in the EDM to perform this translation of object queries to SQL queries, and the relational data to conceptual models.
Once our EDM is ready, we can perform the CRUD operations using the model objects. To be able to perform the CRUD operations, we have to use the ObjectContext
class. Let's try to understand what the ObjectContext
class is and how it can be used to perform the CRUD operations.
Once I have my EDM created, I will have all the entities that I can use in my application. However, I still need a central arbitrator that will let me perform various operations on these entities. This arbitrator in Entity Framework is the ObjectContext
class.
The ObjectContext
class is the main object in Entity Framework. It is the class that is responsible for:
Managing database connection
Providing support to perform CRUD operations
Keeping track of changes in the models so that the models can be updated in the database
The ObjectContext
class can be thought of as an orchestrator that will manage all the entities in the EDM, and lets us perform all of the database operations for these entities.
Note
There is another class, DbContext
, that is very similar to the ObjectContext
class. In fact, the DbContext
class is just a wrapper on top of the ObjectContext
class. It is a rather newer API, and it provides a better API to manage database connections and perform CRUD operations.
Since DbContext
is a better API, we will be using DbContext
to perform all the database operations.
The ObjectContext
class has a SaveChanges
method that we have to call when we want to save the new or changed objects to the database.