An entity is a class representing a table row. DbContext is the session—DbSet<T> properties expose tables, and SaveChangesAsync commits unit-of-work transactions.
Entity example
public class Product {
public int Id { get; set; }
public string Name { get; set; } = "";
public decimal Price { get; set; }
}
DbContext
public class AppDbContext : DbContext {
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) {}
public DbSet<Product> Products => Set<Product>();
}
Basic usage
await _db.Products.AddAsync(product);
await _db.SaveChangesAsync();
Important interview questions and answers
- Q: DbSet vs DbContext?
A: DbSet is a typed table gateway; DbContext coordinates sets, change tracking, and SaveChanges. - Q: Why inject DbContextOptions?
A: Options carry connection string and provider config—supports testing with InMemory provider.
Self-check
- What method persists changes to the database?
- How do you expose a Products table on the context?