LESSON 10 OF 22

10. Migrations, SQL Server Database, and Seed Data

In this lesson, we will execute the EF Core migration workflow, create the SQL Server database, manage schema changes, and prepare controlled development seed data.

45 dk 93

Introduction

In the previous lesson, we configured the DbContext, entity mappings, and relationships used by EF Core. Defining the application model, however, is only part of the data-access workflow. That model must be translated into a real SQL Server database schema.

In this lesson, we will use EF Core migrations to create the database. We will then manage a model change with a new migration and add controlled initial data for the development environment. The goal is not simply to run a few commands, but to understand why migrations are versioned, why migration files belong in source control, and how database initialization fits inside a Clean Architecture solution.

A migration is a versioned description of how the database schema should change as the application model evolves.

Understanding the migration workflow

EF Core compares the current model with the previous model snapshot. When it detects differences such as a new entity, property, relationship, or index, it generates migration code that describes the required database operations.

This approach provides several benefits:

  • Schema changes become traceable and reviewable.
  • Development environments can be created in a repeatable way.
  • The team can apply the same database changes consistently.
  • Database evolution can be included in the normal source-control workflow.

A migration is not the database itself. It is application code that moves a database from one known schema version to another. For that reason, migration files should be reviewed before they are applied, especially when they contain column removal, table removal, or changes to required values.

Preparing packages and tools

In our example, CleanArchitecture.Infrastructure contains the DbContext, while CleanArchitecture.Api is the startup project. The SQL Server provider and design-time package should be referenced by the Infrastructure project.

dotnet add src/CleanArchitecture.Infrastructure package Microsoft.EntityFrameworkCore.SqlServer
dotnet add src/CleanArchitecture.Infrastructure package Microsoft.EntityFrameworkCore.Design

The EF Core command-line tool can be installed globally or as a local tool. A local tool can be useful when a team wants to keep the tool version explicit and consistent.

dotnet tool install --global dotnet-ef
dotnet ef

Keep the EF Core package versions compatible with the target framework and with one another. In a .NET 10 solution, use the EF Core version selected for the project consistently across the provider, design package, and command-line tooling.

Configuring the SQL Server connection

For local development, the connection string can be placed in appsettings.Development.json. Production passwords should not be committed to source control. Use a secret store or environment variables instead.

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

The connection string will be different when using a full SQL Server instance, a container, or Azure SQL. The trust-server-certificate option is suitable only for appropriate local development scenarios; production deployments should use a properly configured certificate.

In Program.cs, call the Infrastructure registration method:

builder.Services.AddInfrastructure(
    builder.Configuration.GetConnectionString("DefaultConnection")!);

The Infrastructure extension method can register the provider and DbContext:

public static IServiceCollection AddInfrastructure(
    this IServiceCollection services,
    string connectionString)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(connectionString));

    return services;
}

This keeps SQL Server-specific details inside Infrastructure. The API layer depends on the Infrastructure registration boundary instead of spreading provider configuration throughout the presentation project.

Creating the first migration

From the solution root, run the following command:

dotnet ef migrations add InitialCreate \
  --project src/CleanArchitecture.Infrastructure \
  --startup-project src/CleanArchitecture.Api \
  --output Persistence/Migrations

The --project option identifies the project where the migration will be created. The --startup-project option identifies the project whose configuration and dependency-injection setup should be used at design time.

This distinction is important in Clean Architecture solutions because the DbContext normally belongs to Infrastructure, while configuration and application startup belong to the API project.

After the command completes, the migration class, metadata file, and model snapshot should appear under the selected folder. Open the migration and verify that the expected tables, foreign keys, indexes, and column nullability were generated.

Applying the migration to SQL Server

Apply pending migrations with:

dotnet ef database update \
  --project src/CleanArchitecture.Infrastructure \
  --startup-project src/CleanArchitecture.Api

If the database does not exist, EF Core creates it and applies the schema. If it already exists, only migrations that have not yet been applied are executed. EF Core tracks applied migrations in a migration-history table.

Open the database with SQL Server Management Studio, Azure Data Studio, or another SQL client. Check that the primary keys, foreign keys, nullable columns, and indexes match the mappings created in the previous lesson.

Managing a model change

Suppose we add a property that indicates whether a product is available:

public bool IsActive { get; private set; } = true;

The database does not change automatically when the class changes. Create another migration:

dotnet ef migrations add AddProductIsActive \
  --project src/CleanArchitecture.Infrastructure \
  --startup-project src/CleanArchitecture.Api \
  --output Persistence/Migrations

Inspect the generated migration. Adding a non-nullable column to a table that already contains rows may require a default value, a temporary nullable column, or a controlled SQL update. Do not assume that every generated operation is safe for existing production data.

To list migrations:

dotnet ef migrations list \
  --project src/CleanArchitecture.Infrastructure \
  --startup-project src/CleanArchitecture.Api

You can generate SQL for review or deployment:

dotnet ef migrations script \
  --project src/CleanArchitecture.Infrastructure \
  --startup-project src/CleanArchitecture.Api

Generating a script is often useful when database changes must be reviewed or applied by a separate deployment process.

What is seed data?

Seed data is initial data inserted into a database during setup or initialization. Examples include product categories, fixed reference values, development products, and default application settings. Seeding and migrations are related but different: migrations version the schema, while seeding manages controlled data initialization.

EF Core supports several approaches:

  • Model-managed data: Use HasData for small, fixed reference data.
  • UseSeeding: Use the current EF Core seeding configuration for general-purpose initialization logic.
  • Custom initialization: Use a dedicated initializer for complex relationships, environment-specific data, or operations such as password hashing.

Do not place large, dynamic, or externally sourced data in HasData. Values such as DateTime.UtcNow, random identifiers, and plain-text passwords can make migrations unstable or unsafe.

Adding development data with UseSeeding

Let us add a development category and a demo product. The code checks whether records already exist, so starting the application multiple times does not create duplicates.

protected override void OnConfiguring(
    DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSeeding((context, _) =>
    {
        var category = context.Set<Category>()
            .FirstOrDefault(x => x.Name == "Electronics");

        if (category is null)
        {
            category = new Category("Electronics");
            context.Set<Category>().Add(category);
            context.SaveChanges();
        }

        var productExists = context.Set<Product>()
            .Any(x => x.Name == "Demo Laptop");

        if (!productExists)
        {
            context.Set<Product>().Add(
                new Product("Demo Laptop", 25000m, category.Id));
            context.SaveChanges();
        }
    });
}

In a real project, move the seeding logic into a separate class or extension method. Also make the environment boundary explicit. Development demo data should not be inserted automatically into a production database.

For fixed lookup data, entity configuration can use HasData:

builder.HasData(
    new Category
    {
        Id = 1,
        Name = "Electronics"
    },
    new Category
    {
        Id = 2,
        Name = "Books"
    });

With HasData, primary key values must be explicit because migrations use them to identify managed rows. This approach is appropriate for small, deterministic reference data that is not expected to change outside migrations. It is not a good fit for users, orders, generated timestamps, passwords, or data obtained from an external service.

Handling design-time DbContext creation

Sometimes dotnet ef cannot construct the DbContext. Common causes include missing configuration, an unavailable connection string, or a DbContext that can only be created after runtime services are built.

A design-time factory can solve this problem:

public sealed class ApplicationDbContextFactory
    : IDesignTimeDbContextFactory<ApplicationDbContext>
{
    public ApplicationDbContext CreateDbContext(string[] args)
    {
        var options = new DbContextOptionsBuilder<ApplicationDbContext>()
            .UseSqlServer(
                "Server=(localdb)\\MSSQLLocalDB;" +
                "Database=CleanArchitectureDb;" +
                "Trusted_Connection=True;" +
                "TrustServerCertificate=True")
            .Options;

        return new ApplicationDbContext(options);
    }
}

The factory is used for design-time operations. Do not hard-code sensitive production credentials in this class. Use user secrets, environment variables, or another secure configuration source.

Common mistakes

  • Using the wrong startup project: The DbContext may be in Infrastructure while configuration and DI are in the API project.
  • Ignoring migration files in source control: Other developers will not have the same schema history.
  • Applying a migration without reviewing it: Drop operations and required-column changes may cause data loss or deployment failures.
  • Mixing EnsureCreated and Migrations: For relational databases managed with migrations, EnsureCreated is generally not the correct initialization mechanism.
  • Seeding demo data in production: Unrestricted initialization code can pollute a real database.
  • Seeding plain-text passwords: Authentication data must be created through a secure hashing and identity workflow.
  • Rewriting applied migrations: Once a migration has been shared or applied, add a new migration instead of changing the old one.

Practice exercise

  1. Add the SQL Server connection string to the development configuration.
  2. Create and apply an InitialCreate migration.
  3. Add the IsActive property to the Product entity.
  4. Create an AddProductIsActive migration.
  5. Generate and inspect the SQL script before applying the migration.
  6. Prepare at least two categories and three products as controlled development seed data.
  7. Run the application twice and verify that duplicate seed records are not created.

Conclusion

In this lesson, we completed the EF Core migration workflow. We prepared the packages and tools, configured SQL Server, created the initial migration, created the database, and managed a model change with a second migration.

We also separated schema versioning from data initialization. Use HasData for small, deterministic reference values and use UseSeeding or a custom initializer for more flexible startup logic. In Clean Architecture, these concerns belong inside Infrastructure so that database-provider details do not leak into the API or application layers.

With this foundation in place, the solution now has a repeatable database setup process. The next lessons can build application features on top of a known schema instead of relying on manually prepared databases.

Sources