The DbContext is the backbone of the Entity Framework Code First. This class is inherited from the system.data.entity.dbcontext namespace. The DbContext is part of the EntityFramework.dll assembly and is installed separately using the NuGet
Table of Contents
What is DbContext
The DbContext is often referred to as the context is the class which is responsible for interacting with the entity model and the database. It allows you to query, insert, update and delete operations on the entities. The older version of the entity framework used objectContext. DbContext is actually a wrapper around the objectContext class.
DbContext manages the lifecycle of entity objects during runtime. It gets the data from the database and populates the objects, tracks their state using change tracking, and finally persists the data to the database.
How to use DbContext
Defining Context Class
The Correct way to use DbContext in our application is by creating a class and deriving from the DbContext. The entities existing in the project can be exposed using the DbSet Property.
1 2 3 4 5 | public class EFContext : DbContext { } |
Passing Connection String to DbContext
The connection string is passed to the Context in its constructor as shown below.
1 2 3 4 5 6 7 8 | public class EFContext :DbContext { public EFContext(): base("Name=EFConstring") { } } |
If the connection string is not specified it is inferred from the DefaultConnectionFactory under the entityFramework section from the web.config
More on Database connection string to DbContext
Exposing Entities via DbSet
The entities existing in the project can be exposed using the DbSet Property. In the following example User model is exposed as DbSet
1 2 3 4 5 6 7 8 9 | public class EFContext :DbContext { public EFContext(): base("Name=EFConstring") { } public DbSet<User> Users {get; set; } } |
Database Initialization
The DbContext exposes the Database object which allows us to create and initialize the database using various initialization strategies. We can also create our own custom strategy to initialize the database. The database initializer also allows us to seed the database with the initial data.
Performing CRUD Operation
Once we have a created context and the DbSets for the entities, we can then perform the CRUD operations on them.
We can add new entity using DbSet.Add or Attach method. The Remove method removes the entity from the DbSet. by Using Find or select methods we can query the database. The results are mapped and returned as entity by the process called materialization.
The SaveChanges method is used to persist the changes back to he database
Context lifetime
The Context must be used with the Using statement so as to correctly manage its lifetime. The using block ensures that the context is disposed or garbage-collected when it is no longer in use
1 2 3 4 5 6 | using (var context = new ProductContext()) { // Perform data access using the context } |
Responsibilities of DbContext
Database Management
DbContext is responsible for Managing the database. It creates the instance of the Database object in the context. The Database object allows you to create, delete, check for the existence of the underlying database Connections
Database Connections
The Database connection is also managed by the DbContext. It Opens the connections as and when needed and closes it when finished the processing of the query
Entity Set
DbContext exposes the property (DbSet<TEntity>) which represent collections of entities in the context. DbContext manages these entities during the lifetime of the entities. It Provides CRUD operations on entity types, such as Add, Attach and Remove.
Querying
DbContext converts LINQ-to-Entities queries to SQL query and sends it to the database. DbSet Inherits from DbQuery API and exposes query capabilities.
Change Tracking
DbContext tracks the changes done to each entity in its lifetime. It keeps track of the state of each entity via change tracker API. The state of the entity can be Added, Unchanged, Modified, deleted and detached etc.
Persisting Data
The DbContext performs all the CRUD related operations to persist the changes made to the database. It also handles the concurrency
Caching
DbContext does first level caching by default. It stores the entities which have been retrieved during the lifetime of a context class.
Model Binding
Reads classes and code-based configurations to build an in-memory model, metadata, and relevant database. It also manages associations between using data annotations/Fluent API.
Materialization
DbContext converts the query results returned by the database into entities. This process called as the materialization
Configuration
The Context Provides API to which allows us to configure the behaviour of the context
Validations
The context Provides automatic validation of data at the data layer. This API makes use of the validation features already built in .NET Framework.
Properties of the DbContext
ChangeTracker
This Property returns the reference to the DbChangeTracker is class which provides features related to change tracking of entities
Configuration
Returns the reference to the DbContextConfiguration. DbContextConfiguration allows us to configure the DbContext
Database
Returns the reference to the database object. The Database instance manages the connection to the database, transactions and all other database related operations.
Methods of the DbContext
SaveChanges()
Saves all changes made using this context to the underlying database. Saves all changes made in this context to the underlying database.
Set(Type) / Set<TEntity>()
Returns the instance of the DbSet for the given entity. You can use the instance to access to entities
Entry(Object) / Entry<TEntity>(TEntity)
Returns the instance of the DbEntityEntry object for the given entity. The DbEntityEntry provides information about the entity and also has the ability to perform actions on the entity.
GetValidationErrors()
Performs the validation on entities tracked by the context. It returns a Collection of DbEntityValidationResult containing validation results.
OnModelCreating (DbModelBuilder)
The OnModelCreating method is called when the context has been initialized. It is called before the model has been locked down. This method returns the reference to the DbModelBuilder object. DbModelBuilder object is used to initialize the context.
Hello
g
bolo