LearnAI ToolsCareerPractice BuildsPlayDevelopmentContact
Lesson 5818 min read

EF Core: DbContext & Models

Learn how to define entity models and a DbContext to represent your database in C#.

On this page 6 sections

Entity Classes

An entity is a plain C# class that EF Core maps to a database table. By convention, a property named Id (or {ClassName}Id) becomes the primary key.

public class TaskItem
{
public int Id { get; set; }
public string Title { get; set; } = "";
public bool IsComplete { get; set; }
}

DbContext

A DbContext represents a session with the database — it exposes DbSet<T> properties for each entity type, giving you a queryable, LINQ-friendly view of each table.

public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
public DbSet<TaskItem> Tasks { get; set; }
}

Registering DbContext

Program.cs
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

Migrations

Migrations let EF Core translate changes in your C# entity classes into the SQL needed to update your actual database schema.

dotnet ef migrations add InitialCreate
dotnet ef database update

FAQs

Yes — run dotnet tool install --global dotnet-ef once to get the dotnet ef command available.

Summary

  • Entity classes are plain C# classes mapped to database tables.
  • DbContext exposes DbSet<T> properties for querying each table.
  • Migrations translate C# model changes into actual database schema updates.
Next Lesson →

EF Core CRUD Operations