DbContext is the main class you use to work with the database in EF Core. It represents a session with the database and implements the Unit of Work pattern. It collects your changes and writes them together.
It manages the database connection, translates LINQ queries into SQL, and tracks changes to the entities it manages. Each tracked entity has a state such as Added, Modified or Deleted. When you call SaveChanges, the context writes those changes in a transaction.
public class ApplicationDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("connection-string");
}
}
A DbContext is short-lived and not thread-safe, so use one instance per unit of work, such as one web request.
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓