C# Interview Question #171
What is DbContext in Entity Framework Core?
EF Core, Data Access & Performance Senior Advanced
Quick Interview Answer
DbContext represents a session with the database and coordinates querying, change tracking, and saving entities.
Detailed Explanation
DbContext represents a session with the database and coordinates querying, change tracking, and saving entities.
It exposes DbSet<TEntity> properties or Set<TEntity>() for entity sets and acts as a Unit of Work for tracked changes.
DbContext is not thread-safe and should not be used concurrently from multiple operations. In ASP.NET Core it is normally registered with a scoped lifetime, giving one context instance per request scope.
Code Example
public class AppDbContext : DbContext
{
public AppDbContext(
DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Product> Products => Set<Product>();
}