LESSON 5 OF 16

5. DbContext, Migrations, and Database Configuration

This lesson demonstrates configuring Entity Framework Core DbContext, managing SQL Server connection strings securely, creating migrations, and keeping the database schema synchronized with code.

75 dk 65

Introduction

In the previous lessons, we separated the solution into layers and created domain models and DTO contracts. In this lesson, we will establish real communication between the application and SQL Server. We will configure an Entity Framework Core DbContext, read the connection string through the ASP.NET Core configuration system, and transfer our model to the database using migrations.

The main goal is to keep database concerns inside the data access layer instead of placing connection and persistence logic in controllers or the web layer. This keeps the architecture maintainable and allows the application to use different connection settings in development, testing, and production. When the model changes, controlled migration files can be used to evolve the database schema without recreating the entire database.

Example project: We will use a product catalog application. The example includes a Product entity, a relationship with Category, and the basic infrastructure required to persist products.

What Is DbContext?

DbContext is the Entity Framework Core class that represents a session and unit of work between the application and the database. It maps entity classes to database tables, translates LINQ queries into SQL, tracks changes, and sends those changes to the database through SaveChanges or SaveChangesAsync.

A context class commonly exposes one DbSet<T> property for each entity. These properties provide the starting point for querying and modifying data.

Creating ApplicationDbContext

In a layered architecture, the DbContext belongs in the infrastructure or data access project. Add a class similar to the following:

using Microsoft.EntityFrameworkCore;
using ProductCatalog.Domain.Entities;

namespace ProductCatalog.Infrastructure.Persistence;

public sealed class ApplicationDbContext : DbContext
{
    public ApplicationDbContext(
        DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<Product> Products => Set<Product>();
    public DbSet<Category> Categories => Set<Category>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfigurationsFromAssembly(
            typeof(ApplicationDbContext).Assembly);

        base.OnModelCreating(modelBuilder);
    }
}

The DbContextOptions<ApplicationDbContext> constructor parameter allows configuration to be supplied from outside the context. This is more flexible than hard-coding a connection string inside the class. The same context can therefore run against different databases or environments without changing its source code.

Separating Entity Configuration

Rather than placing all table and column rules inside OnModelCreating, create a separate configuration class for each entity. These classes implement IEntityTypeConfiguration<T>.

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using ProductCatalog.Domain.Entities;

namespace ProductCatalog.Infrastructure.Persistence.Configurations;

public sealed class ProductConfiguration
    : IEntityTypeConfiguration<Product>
{
    public void Configure(EntityTypeBuilder<Product> builder)
    {
        builder.ToTable("Products");

        builder.HasKey(product => product.Id);

        builder.Property(product => product.Name)
            .HasMaxLength(150)
            .IsRequired();

        builder.Property(product => product.Description)
            .HasMaxLength(1000);

        builder.Property(product => product.Price)
            .HasPrecision(18, 2)
            .IsRequired();

        builder.HasOne(product => product.Category)
            .WithMany(category => category.Products)
            .HasForeignKey(product => product.CategoryId)
            .OnDelete(DeleteBehavior.Restrict);
    }
}

The ApplyConfigurationsFromAssembly call discovers and applies configuration classes from the same assembly. The context remains focused on infrastructure while table names, required fields, lengths, precision, and relationships are defined in dedicated, testable classes.

Adding the SQL Server Provider

EF Core uses provider packages to implement database-specific behavior. Add the Microsoft.EntityFrameworkCore.SqlServer package to the data access project, using a version compatible with the .NET and EF Core major versions used by the solution.

dotnet add ProductCatalog.Infrastructure package Microsoft.EntityFrameworkCore.SqlServer

The EF Core command-line tool is required for migration commands. Install it globally or update an existing installation:

dotnet tool install --global dotnet-ef

# If the tool is already installed
dotnet tool update --global dotnet-ef

Do not mix unrelated EF Core major versions. For example, a SQL Server provider from one major version should not be paired arbitrarily with a different EF Core major version. Keeping the EF Core, relational, and SQL Server packages compatible reduces design-time and runtime problems.

Configuring the Connection String

Hard-coding a connection string inside ApplicationDbContext makes environment changes difficult and can expose credentials in source control. Instead, use the ConnectionStrings section of ASP.NET Core configuration.

For local development, a template such as the following can be placed in ProductCatalog.Api/appsettings.json:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=ProductCatalogDb;Trusted_Connection=True;TrustServerCertificate=True;"
  }
}

Never place production passwords, access keys, or other secrets in this file. During development, use User Secrets. In deployment, use environment variables or a managed secret store. A file committed to source control should contain only a safe example or a local connection that does not expose credentials.

Initialize User Secrets from the directory containing the API project:

dotnet user-secrets init

dotnet user-secrets set "ConnectionStrings:DefaultConnection" "Server=(localdb)\\MSSQLLocalDB;Database=ProductCatalogDb;Trusted_Connection=True;TrustServerCertificate=True;"

Hierarchical configuration keys are commonly represented with double underscores in environment variables:

ConnectionStrings__DefaultConnection

Registering DbContext in Program.cs

Read the connection string and register the context with the dependency injection container in the API project's Program.cs file:

using Microsoft.EntityFrameworkCore;
using ProductCatalog.Infrastructure.Persistence;

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration
    .GetConnectionString("DefaultConnection")
    ?? throw new InvalidOperationException(
        "The DefaultConnection connection string was not found.");

builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
    options.UseSqlServer(connectionString, sqlOptions =>
    {
        sqlOptions.EnableRetryOnFailure(
            maxRetryCount: 5,
            maxRetryDelay: TimeSpan.FromSeconds(10),
            errorNumbersToAdd: null);
    });
});

builder.Services.AddControllers();

var app = builder.Build();

app.MapControllers();
app.Run();

AddDbContext registers the context as a scoped service by default. Treating one HTTP request as one unit of work is a suitable default for many web applications. Registering DbContext as a singleton is usually incorrect because DbContext is not thread-safe and should not be shared across unrelated requests.

Creating the Initial Migration

First verify that the solution builds successfully:

dotnet build

In this example, the context is located in ProductCatalog.Infrastructure, while the startup project is ProductCatalog.Api. Create the initial migration by specifying both projects:

dotnet ef migrations add InitialCatalog \
  --project ProductCatalog.Infrastructure \
  --startup-project ProductCatalog.Api \
  --output-dir Persistence/Migrations

The command compares the current entity model with the existing model snapshot and generates source files that describe the schema changes. The migration directory normally contains a migration class, a model snapshot, and supporting files. These files should be committed to source control because they are part of the database schema history.

Always review generated migration code before applying it. Pay particular attention to table drops, column drops, renames, and other operations that may cause data loss.

Applying the Migration

Apply pending migrations to the local SQL Server database with the following command:

dotnet ef database update \
  --project ProductCatalog.Infrastructure \
  --startup-project ProductCatalog.Api

EF Core records applied migrations in a history table. It can therefore determine which migrations have already been applied and execute only the pending ones.

List the migrations in the project with:

dotnet ef migrations list \
  --project ProductCatalog.Infrastructure \
  --startup-project ProductCatalog.Api

If the latest migration has not been shared or applied yet, it can be removed:

dotnet ef migrations remove \
  --project ProductCatalog.Infrastructure \
  --startup-project ProductCatalog.Api

This command is not a general-purpose rollback mechanism for a migration already applied to a shared database. For an applied change, plan a controlled rollback or create a new corrective migration after evaluating the data implications.

Design-Time DbContext Problems

Migration commands create the DbContext at design time. If the startup project is incorrect or configuration is missing, you may see errors such as:

  • The DbContext could not be created.
  • The DefaultConnection connection string was not found.
  • No suitable DbContextOptions constructor was found.
  • The wrong project or assembly was selected.

When context creation becomes complex, implement IDesignTimeDbContextFactory<ApplicationDbContext>. The factory is used for design-time operations such as migrations. Even in the factory, avoid hard-coding credentials; read configuration from User Secrets, environment variables, or another appropriate configuration source.

Common Mistakes

  • Committing a password to Git: Keep secrets out of appsettings files and source code.
  • Using the wrong startup project: When the context is in another project, specify --project and --startup-project.
  • Deleting migration files manually: This can break schema history. Keep migrations under source control and remove only an unshared migration through the EF tool.
  • Dropping the database for every model change: This may be acceptable for temporary experiments, but it destroys real data.
  • Registering DbContext as a singleton: Sharing a context across requests can cause tracking and concurrency problems.
  • Applying migrations without review: Renames and column deletions may produce destructive SQL.
  • Mixing EF Core package versions: Use compatible versions for Microsoft.EntityFrameworkCore, Relational, and SqlServer.

Practice Exercise

Complete the following exercise:

  1. Add an integer property named StockQuantity to the Product entity, with zero as its default value.
  2. Decide how the domain layer should prevent negative stock quantities.
  3. Configure the property as required with a database default in ProductConfiguration.
  4. Create a migration named AddStockQuantity.
  5. Review the migration and verify that the column is added to the correct table.
  6. Apply the migration to the local SQL Server database.
  7. Inspect the table using SQL Server Management Studio or Azure Data Studio.

As an additional task, move the connection string into User Secrets and confirm that the application still starts and the migration command still works.

Conclusion

In this lesson, we created the main integration points between EF Core and SQL Server. We placed the DbContext in the data access layer, separated entity configuration into dedicated classes, added the SQL Server provider, and read the connection string from ASP.NET Core configuration. We then created and applied an initial migration.

You can now track changes between the code model and database schema as part of the application source code. In the next lessons, we will use this context through repository or service components to implement querying, insertion, updating, and deletion while preserving the rules of the layered architecture.

Sources