junioref-core
DbContext is a Unit of Work + Repository. It tracks entity changes and generates SQL. Lifetime: Scoped (one per HTTP request).
DbContext manages the connection, change tracking, and SaveChanges() generates INSERT/UPDATE/DELETE. It is not thread-safe — it cannot be used from multiple threads. It is registered as Scoped via AddDbContext<T>. Dispose closes the connection. DbSet<T> is a collection of entities of one type, mapped to a table.
public class AppDbContext : DbContext
{
public DbSet<User> Users => Set<User>();
public DbSet<Order> Orders => Set<Order>();
protected override void OnModelCreating(ModelBuilder b)
{
b.Entity<User>().HasIndex(u => u.Email).IsUnique();
b.Entity<Order>().HasOne(o => o.User)
.WithMany(u => u.Orders);
}
}
// Registration (Scoped by default)
builder.Services.AddDbContext<AppDbContext>(o =>
o.UseNpgsql(connectionString));When yes
The primary way to work with a database in .NET. CRUD, migrations, LINQ queries
When no
High-performance bulk operations (use Dapper or SqlBulkCopy). Real-time with very high RPS — tracking overhead
Interview tip
DbContext = Unit of Work. SaveChanges() is a single transaction. Never register it as Singleton.