wasAsked.

What are DbContext and DbSet in Entity Framework Core?

Frequently Asked (All Companies) · Role not specified · technical

Published

Year not specified · Entity Framework Core, .NET

Community answers

Posted by wasAsked editorial collection

DbContext and DbSet are the two central classes in Entity Framework Core. DbContext - Represents a session with the database and acts as a combination of the Unit of Work and Repository patterns. - Responsibilities: - Managing the database connection. - Configuring the model (entities, relationships, keys, indexes) through OnModelCreating or configuration classes. - Querying data through LINQ. - Change tracking: remembering loaded entities and detecting changes. - Saving changes: SaveChanges or SaveChangesAsync generates INSERT, UPDATE and DELETE statements in a transaction. - Transactions (Database.BeginTransactionAsync), raw SQL, migrations. public class ShopDbContext(DbContextOptions<ShopDbContext> options) : DbContext(options) { public DbSet<Product> Products => Set<Product>(); public DbSet<Order> Orders => Set<Order>(); protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Product>(b => { b.Property(p => p.Name).HasMaxLength(200).IsRequired(); b.Property(p => p.Price).HasPrecision(18, 2); b.HasIndex(p => p.Sku).IsUnique(); }); modelBuilder.ApplyConfigurationsFromAssembly(typeof(ShopDbContext).Assembly); } } Registration in ASP.NET Core: builder.Services.AddDbContext<ShopDbContext>(o => o.UseSqlServer(builder.Configuration.GetConnectionString("Shop"))); DbSet<TEntity> - Represents a collection of entities of one type — usually mapped to a table. - Starting point for LINQ queries (it implements IQueryable<TEntity>) and for adding or removing entities. // Query var cheap = await db.Products.Where(p => p.Price < 500).OrderBy(p => p.Name).ToListAsync(ct); // Find by primary key (checks the change tracker first) var product = await db.Products.FindAsync([id], ct); // Add db.Products.Add(new Product { Name = "Mouse", Price = 799, Sku = "MS-01" }); // Update a tracked entity product!.Price = 749; // Remove db.Products.Remove(product); await db.SaveChangesAsync(ct); // all changes saved in one transaction How change tracking works - Entities returned by queries are tracked with a state: Added, Unchanged, Modified, Deleted or Detached. - SaveChanges detects changes (snapshot comparison) and generates the minimal SQL needed. - Use AsNoTracking() for read-only queries to avoid tracking overhead. Lifetime and threading - DbContext is designed to be short-lived: one instance per unit of work. In ASP.NET Core, AddDbContext registers it as scoped (one per HTTP request). - It is not thread-safe: never use one instance from multiple threads concurrently. - For singletons and background services, use IDbContextFactory<T> to create contexts per operation; for high throughput, consider AddDbContextPool. - Dispose it when done (DI does this automatically). Interview summary: "DbContext is the session with the database: it configures the model, tracks changes, runs queries and saves changes as a unit of work. DbSet<T> represents a table-like collection of entities used for LINQ queries and for adding, updating and removing entities."

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics