Roadmap › Entity Framework (EF6 & EF Core) › Module: Getting Started
Lessons in this course (15)

2. DbContext, DbSet and configuration

Basic★ Must knowLesson 2 of 15
csharp
public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
    public DbSet<Customer> Customers => Set<Customer>();
    public DbSet<Order> Orders => Set<Order>();

    protected override void OnModelCreating(ModelBuilder b)
    {
        b.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);   // IEntityTypeConfiguration<T> classes
    }
}

public class Customer
{
    public int Id { get; set; }                               // convention: primary key
    public required string Name { get; set; }
    public string? Email { get; set; }
    public List<Order> Orders { get; set; } = [];             // navigation (one-to-many)
}

public class Order
{
    public int Id { get; set; }
    public int CustomerId { get; set; }                       // foreign key by convention
    public Customer Customer { get; set; } = null!;
    public decimal Total { get; set; }
    public DateTime CreatedAt { get; set; }
}

// Program.cs
builder.Services.AddDbContext<AppDbContext>(o =>
    o.UseSqlServer(builder.Configuration.GetConnectionString("Db"), sql => sql.EnableRetryOnFailure()));

AddDbContextPool reuses context instances for high-throughput apps; AddDbContextFactory + IDbContextFactory<T> for Blazor Server, background services and parallel work.