Context Class in Entity Framework
Sardar Mudassar Ali Khan
Posted on May 31, 2023
In Entity Framework, a context class represents a database session and acts as a bridge between your application and the underlying database. It is responsible for managing the connection and providing a set of methods to interact with the database.
The context class is derived from the DbContext base class provided by Entity Framework. It serves as a container for all the entity sets (DbSet) representing the tables or collections in the database.
Typically, you create a context class that inherits from DbContext and define properties for each entity set you want to interact with. These entity sets represent tables or collections in your database, and Entity Framework uses them to generate SQL queries and perform CRUD operations.
Here's an example of a context class in Entity Framework:
using Microsoft.EntityFrameworkCore;
public class MyDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
public DbSet<Order> Orders { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Configure the database provider and connection string
optionsBuilder.UseSqlServer("YourConnectionString");
}
}
In this example, the MyDbContext
class inherits from DbContext
and defines two properties: Customers
and Orders
. These properties represent the entity sets that map to the "Customers" and "Orders" tables in the database.
The OnConfiguring
method is overridden to specify the database provider and connection string. In this case, it's using SQL Server with a connection string named "YourConnectionString."
Once you have defined the context class, you can use it to query, insert, update, and delete data in the database using Entity Framework's LINQ (Language Integrated Query) syntax. You can also use it to configure various aspects of the database, such as defining relationships between entities, specifying indexes, and more.
The context class in Entity Framework plays a vital role in managing the connection and providing an interface to interact with the database using entity classes.
Posted on May 31, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.