Part 2: Entity Framework Core & SQL Setup

Part 2 Technology Updated September 12, 2026

In this part, we set up Entity Framework Core with SQL Server, create our DbContext, and run our first migration.

1. Install NuGet Packages

Add the required EF Core packages to your Infrastructure project:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet add package Microsoft.EntityFrameworkCore.Tools

2. Create Application DbContext

Create the AppDbContext.cs class extending EF Core's DbContext:

using Microsoft.EntityFrameworkCore;

namespace Infrastructure.Data;

public class AppDbContext : DbContext 
{
    public AppDbContext(DbContextOptions options) : base(options) 
    {
    }

    public DbSet Products => Set();
    public DbSet Categories => Set();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyConfigurationsFromAssembly(typeof(AppDbContext).Assembly);
    }
}

3. Running Database Migrations

Execute the following commands in the terminal to generate and apply your migrations:

# Generate the migration
dotnet ef migrations add InitialCreate --startup-project ../WebApi

# Apply migration to SQL Server database
dotnet ef database update --startup-project ../WebApi

The database schema is now synchronized with your domain models.