SkillByAIOpen interactive version →

Lesson 18 / 26

Entities and DbContext

Define an entity, a DbContext and register it with a connection string.

The DbContext

EF Core is an object-relational mapper. A DbContext represents a session with the database, and each DbSet<T> property represents a table. It tracks the changes you make and writes them on SaveChanges.

Code to database

Entity classes map to tables, migrations change the schema, and LINQ queries become SQL.

Figure 6.1 — Model, migration, database, query.

A small model

SQLite keeps the example simple; the same code works with SQL Server or PostgreSQL by swapping the provider package.

public class Book
{
    public int Id { get; set; }
    public required string Title { get; set; }
    public decimal Price { get; set; }
}

public class ShopDb(DbContextOptions<ShopDb> options) : DbContext(options)
{
    public DbSet<Book> Books => Set<Book>();
}

// Program.cs
builder.Services.AddDbContext<ShopDb>(o =>
    o.UseSqlite(builder.Configuration.GetConnectionString("Default")));

Keep DbContext scoped

AddDbContext registers it as scoped, and that is correct: it is not thread-safe, so never share one instance between concurrent requests.

Quick check: What does a DbSet<Book> property usually represent?

  • A database server
  • A table of books
  • A migration file
  • A connection string
Answer

A table of books — Each `DbSet<T>` maps to a table (or view) holding rows for the entity type.