Updated March 15, 2023
Introduction to Entity Framework DbContext
Entity Framework DbContext is the class where it is the bridge between the entity classes and the database. The DbContext is an integral part of the Entity Framework and is the primary class that is dependable for interacting with the database. An instance of DbContext signifies the session with the database used for querying and storing the instances of entities in the database. Entity Framework DbContext is the combination of repository patterns and units of work.
Overview of Entity Framework DbContext
DbContext is the brain of EF, which does the entire communications with the database and is the backbone for the EF Code First approach. This class is inherited from the namespace System.Data.Entity.DbContext and the DbContext are part of EntityFramework.dll assembly which is installed individually at the NuGet package manager. Entity Framework DbContext is the class where it is the bridge between the domain or entity classes and the database.
The major class responsible for interacting with data objects is called System.Data.Entity.DbContext. The DbContext API is more frequent and flexible, releasing innovative features to DbContext and Code-First API; the EF team distributes the EntityFramework.dll through the MS NuGet feature.
- NuGet enables to include the references to the .NET projects by dragging the dll’s directly into the project from the web.
- DbContext API simplifies the interactions with EF and diminishes the methods we used and properties required to access frequently used tasks.
- The Context class controls the entity objects during execution, including objects with data from the database, persisting data to db, and changing tracking.
Entity Framework DbContext Class
The DbContext class is an introductory class in EF API, and it is the bridge between the entity classes or domain and the database. Entity Framework DbContext is the combination of repository patterns and units of work.
It is responsible for the activities such as follows:
- Querying: The querying activity is nothing but converting the LINQ to Entities queries to the SQL queries and sending them back to the database.
- Change Tracking: The change tracking activity keeps track of changes on entities once querying from the database.
- Persisting Data: This activity performs the CRUD operations like inserting, deleting, update to the database based on entity states.
- Caching: This activity offers the level of caching by default and stores the entities retrieved during the entire time of the context class.
- Objects Materialization: This activity converts the data raw from the database into the objects of the entity.
- Manage Relationship: This activity manages the relationships between the SSDL, CSDL, and MSL in the Database-First or Model-First approach using the Fluent API configuration in the Code-First approach.
Adding Entity Framework DbContext
To add the Entity Framework DbContext class in the application, we must build the class that derives the DbContext class available in Microsoft.EntityFramework namespace. To create the class file names ” and inherit the class from the DbContext class as shown below, you wish you could give any name for DbContext class here. I provided the name CompanyDbContext.
Code:
public class CompanyDbContext : DbContext
{
}
We have to perform tasks by the DbContext class we require to an instance DbContextOptions class. The instance contains the required information like connection string, provider of database, and so on. To pass the ContextOptions instance, we make use of the constructor of CompanyDbContext class as shown,
Code:
public CompanyDbContext (DbContextOptions< CompanyDbContext > options)
: base(options)
{
}
Let’s see the Entity Framework DbContext class, which contains the property DbSet<TEntity> used for every entity in the application.
Just create two entities as Company and Orders as follows:
Company:
Code:
public class CompanyTable
{
public int CompId { get; set; }
public string CmName { get; set; }
public string CmAddress { get; set; }
public string Cm_ContactNo { get; set; }
public Nullable<System.DateTime> Curr_date { get; set; }
}
Order:
Code:
public class Order
{
public int O_Id { get; set; }
public int OrderNo { get; set; }
public Nullable<int> CompId { get; set; }
}
The application contains two entities, so the CompanyDbContext class and we have two DbSet Properties as shown below:
Code:
public partial class CompanyDbContext : DbContext
{
public CompanyDbContext (DbContextOptions< CompanyDbContext > options)
: base(options)
{
}
public DbSet<CompanyTable> CompanyTables { get; set; }
public DbSet<Order> cmOrders { get; set; }
}
The DbSet properties like CompanyTable and Orders will perform the entire operations.
Let’s see the following DbContext class; this class derives from the DbContext to add the details of the company by using Entity Framework as follows:
Code:
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class CompanyDbContext: DbContext
{
public CompanyDbContext ()
: base("name= CompanyDbContext ")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<CompanyTable> CompanyTables { get; set; }
public DbSet<Order> cmOrders { get; set; }
}
To add the details to the database, including the following code:
Code:
using (CompanyDbContext context = new CompanyDbContext ())
{
//to add new company to the database
var addCompany = new CompanyTable
{
CmName ="GlassWorkApplications",
CmAddress ="Chennai",
Cm_ContactNo ="9908876510"
};
context.CompanyTables.Add(addCompany);
context.SaveChanges();
}
Output:
Entity Framework DbContext Data Operations
DbContext is the brain of EF, which does the entire communications with the database and is the backbone for the EF Code First approach. The DbContext is the part of the EntityFramework.dll assembly that is installed individually at the NuGet package manager. Entity Framework DbContext is the class where it is the bridge between the entity or types and the database.
There are a few methods of operations in DbContext class as follows:
- Add: It adds the new entity with the state of added.
- AddRange: It adds the collection of new entities with the state of added.
- Attach: This method attaches the new or the existing entity with the unchanged state.
- AttachRange: This method connects the collection of a new or existing entity with a state of unchanged.
- Remove: It attaches the entity with the deleted state.
- RemoveRange: This method secures the collection of entities with the deleted state.
- Update: This method connects the disconnected data entity with the modified state.
- UpdateRange: This method ensures the collection of a disconnected entity with the modified state.
- SaveChanges: This method executes the commands of INSERT, UPDATE, and DELETE to the database for the entities with modified state, added state, or deleted state.
- OnModelCreating: This operation overrides the method configuration model discovered by convention from the entity types in DbSet<TEntity> Properties on derived context.
Conclusion
This article has seen the DbContext, EF’s brain, and the bridge between entity classes and databases. EF DbContext is explained programmatically by adding the records for better understanding.
Recommended Articles
We hope that this EDUCBA information on “Entity Framework DbContext” was beneficial to you. You can view EDUCBA’s recommended articles for more information.