EF Core - DbContext

In Entity Framework Core (EF Core), the DbContext is the primary class responsible for interacting with the database. It manages the database connection, tracks changes to entities, and handles CRUD operations. This tutorial explores the key aspects of configuring and using DbContext in your applications.


1. Purpose of DbContext

The DbContext class serves several essential roles in an EF Core application:


2. Creating a DbContext

To create a DbContext, define a class that inherits from DbContext and configure the database connection and entity sets.

        
            
public class ApplicationDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("YourConnectionStringHere");
    }
}
        
    

In this example, ApplicationDbContext is a DbContext that includes a DbSet<Product> for querying and saving instances of the Product entity.


3. Configuring DbContext

You can configure the DbContext by overriding the OnConfiguring method or using a configuration file like appsettings.json.

Using OnConfiguring Method:

        
            
public class ApplicationDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("YourConnectionStringHere");
    }
}
        
    

Using appsettings.json:

        
            
{
  "ConnectionStrings": {
    "DefaultConnection": "Server=localhost;Database=EFCoreDemo;Trusted_Connection=True;"
  }
}
        
    

DbContext with Configuration:

        
            
public class ApplicationDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
    }
}
        
    

4. Using DbContext

The DbContext provides a range of methods for interacting with your database, including querying, adding, updating, and deleting entities.

        
            
using (var context = new ApplicationDbContext())
{
    // Query all products
    var products = context.Products.ToList();

    // Add a new product
    var newProduct = new Product { Name = "New Product", Price = 99.99m };
    context.Products.Add(newProduct);

    // Save changes to the database
    context.SaveChanges();
}
        
    

In this example, we use ApplicationDbContext to retrieve all products, add a new product, and save changes to the database.


5. Best Practices

Here are some best practices for using DbContext effectively:


Summary

The DbContext is a crucial component of EF Core, providing the necessary functionality to interact with databases efficiently. By understanding its configuration and usage, developers can build robust applications that effectively manage data access and persistence.