Prior to EntityFramework 4.1, EDM used to generate context classes that were derived from the ObjectContext class. It was a little tricky to work with ObjectContext. DbContext is conceptually similar to ObjectContext. It is a wrapper around ObjectContext which is useful in all the development models: Code First, Model First and Database First.
DbContext is an important part of Entity Framework. It is a bridge between your domain or entity classes and the database.
DbContext is the primary class that is responsible for interacting with data as object. DbContext is responsible for the following activities:
- EntitySet: DbContext contains entity set (DbSet<TEntity>) for all the entities which is mapped to DB tables.
- Querying: DbContext converts LINQ-to-Entities queries to SQL query and send it to the database.
- Change Tracking: It keeps track of changes that occurred in the entities after it has been querying from the database.
- Persisting Data: It also performs the Insert, Update and Delete operations to the database, based on what the entity states.
- Caching: DbContext does first level caching by default. It stores the entities which have been retrieved during the life time of a context class.
- Manage Relationship: DbContext also manages relationship using CSDL, MSL and SSDL in DB-First or Model-First approach or using fluent API in Code-First approach.
Object Materialization: DbContext converts raw table data into entity objects.