Introduction

If you have ever configured EF Core Migrations in a simple project with a single csproj, you know it is reasonably straightforward: dotnet ef migrations add, dotnet ef database update and you’re done. But the reality of enterprise projects is different. Your solution has multiple projects β€” API, Domain, IoC, Infra.Data.PostgreSQL, Infra.Bus, Infra.Http, Infra.Dto β€” and the DbContext doesn’t live in the same project as the entry point. Now add dotnet secrets to manage connection strings securely, the need to scaffold legacy databases that already exist, and a team with 5 or 10 developers creating migrations at the same time.

In this article, I will solve each of these problems in practice. I will configure migrations in a real multi-layer solution, use dotnet user-secrets for connection strings (no passwords in appsettings.json), reverse engineer existing databases with Scaffold-DbContext, and establish concrete strategies to avoid migration conflicts in large teams. If you are not yet familiar with the advanced Fluent API mapping that generates these migrations, I recommend first reading EF Core 8 Fluent API: Mapping, ORM and Decoupling.

πŸ“¦ Source code: The complete implementation of this article is in the blog-zocateli-sample repository on GitHub. Clone it, explore it and adapt it to your context.


Multi-Layer Project Structure

Before talking about migrations, it is essential to understand the project structure. It is a .NET 8 solution with separation of responsibilities across multiple csproj files:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
MeuEcommerce.sln
β”‚
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ MeuEcommerce.Api/                    # Entry point β€” ASP.NET Core Web API
β”‚   β”‚   β”œβ”€β”€ Program.cs
β”‚   β”‚   β”œβ”€β”€ Controllers/
β”‚   β”‚   └── appsettings.json
β”‚   β”‚
β”‚   β”œβ”€β”€ MeuEcommerce.Domain/                 # Entities and interfaces β€” NO EF Core dependency
β”‚   β”‚   β”œβ”€β”€ Entities/
β”‚   β”‚   β”‚   β”œβ”€β”€ Produto.cs
β”‚   β”‚   β”‚   β”œβ”€β”€ Categoria.cs
β”‚   β”‚   β”‚   └── ...
β”‚   β”‚   └── Interfaces/
β”‚   β”‚       └── IProdutoRepository.cs
β”‚   β”‚
β”‚   β”œβ”€β”€ MeuEcommerce.IoC/                    # Dependency injection β€” registers everything
β”‚   β”‚   └── DependencyInjection.cs
β”‚   β”‚
β”‚   β”œβ”€β”€ MeuEcommerce.Infra.Data.PostgreSQL/  # EF Core + Migrations (DbContext lives HERE)
β”‚   β”‚   β”œβ”€β”€ AppDbContext.cs
β”‚   β”‚   β”œβ”€β”€ Configurations/
β”‚   β”‚   β”‚   β”œβ”€β”€ ProdutoConfiguration.cs
β”‚   β”‚   β”‚   └── CategoriaConfiguration.cs
β”‚   β”‚   β”œβ”€β”€ Repositories/
β”‚   β”‚   β”‚   └── ProdutoRepository.cs
β”‚   β”‚   β”œβ”€β”€ Migrations/                      # Migrations generated here
β”‚   β”‚   └── DesignTimeDbContextFactory.cs    # Factory for the EF CLI
β”‚   β”‚
β”‚   β”œβ”€β”€ MeuEcommerce.Infra.Bus/             # Messaging (RabbitMQ, Azure Service Bus)
β”‚   β”œβ”€β”€ MeuEcommerce.Infra.Http/            # HttpClient for external APIs
β”‚   └── MeuEcommerce.Infra.Dto/             # Shared DTOs
β”‚
└── tests/
    └── MeuEcommerce.Tests/

Critical point: The DbContext lives in Infra.Data.PostgreSQL, but the entry point (Program.cs) lives in Api. The EF Core CLI needs both to work β€” it needs the DbContext to generate migrations and the entry point to resolve connection strings and dependencies.

ℹ️ Info: This structure follows the Layered Architecture / Clean Architecture pattern where the Domain has no dependency on infrastructure. If you want to understand the architectural patterns behind this organization, see Software Architecture: GoF, Patterns and Microservices.


Prerequisites

  • .NET 8.0 SDK or later
  • dotnet-ef tool (EF Core CLI):
1
2
3
4
5
6
7
dotnet tool install --global dotnet-ef

# Or update to the latest version
dotnet tool update --global dotnet-ef

# Verify the installation
dotnet ef --version
  • NuGet packages in the Infra.Data.PostgreSQL project:
1
2
3
4
5
cd src/MeuEcommerce.Infra.Data.PostgreSQL

dotnet add package Microsoft.EntityFrameworkCore --version 8.0.*
dotnet add package Npgsql.EntityFrameworkCore.PostgreSQL --version 8.0.*
dotnet add package Microsoft.EntityFrameworkCore.Design --version 8.0.*

⚠️ Warning: The Microsoft.EntityFrameworkCore.Design package is required for the EF Core CLI to work. It can be added to the data project OR to the startup project. If it is only in the startup project, use --startup-project when running the commands.


Configuring Migrations in a Multi-Project Solution

The Problem

When you run dotnet ef migrations add without additional configuration, the CLI tries to find the DbContext and its dependencies in the current project. In a multi-layer project, this fails with errors like:

1
2
Unable to create a 'DbContext' of type 'AppDbContext'.
The exception 'Unable to resolve service for type...' was thrown.

The CLI needs two pieces of information:

  1. Where the DbContext is (--project) β€” in Infra.Data.PostgreSQL
  2. Where the entry point is (--startup-project) β€” in Api (to resolve DI and the connection string)

Solution 1: CLI Parameters (Quick)

1
2
3
4
5
6
7
8
9
# From the solution root
dotnet ef migrations add InitialCreate \
  --project src/MeuEcommerce.Infra.Data.PostgreSQL \
  --startup-project src/MeuEcommerce.Api \
  --output-dir Migrations

dotnet ef database update \
  --project src/MeuEcommerce.Infra.Data.PostgreSQL \
  --startup-project src/MeuEcommerce.Api

It works, but it is verbose. For every migration you need to remember the paths.

Create a factory in the Infra.Data.PostgreSQL project that the CLI uses at design time β€” without depending on the API’s Program.cs:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;

namespace MeuEcommerce.Infra.Data.PostgreSQL;

/// <summary>
/// Factory used ONLY by the EF Core CLI (dotnet ef migrations add/update).
/// At runtime, the DbContext is resolved by the DI configured in IoC.
/// </summary>
public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<AppDbContext>
{
    public AppDbContext CreateDbContext(string[] args)
    {
        // Reads the connection string from user-secrets or environment variables
        var configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true)
            .AddUserSecrets<DesignTimeDbContextFactory>(optional: true)
            .AddEnvironmentVariables()
            .Build();

        var connectionString = configuration.GetConnectionString("DefaultConnection")
            ?? throw new InvalidOperationException(
                "Connection string 'DefaultConnection' not found. " +
                "Configure it via 'dotnet user-secrets set' or an environment variable.");

        var optionsBuilder = new DbContextOptionsBuilder<AppDbContext>();
        optionsBuilder.UseNpgsql(connectionString, npgsql =>
        {
            npgsql.MigrationsAssembly(
                typeof(DesignTimeDbContextFactory).Assembly.FullName);
        });

        return new AppDbContext(optionsBuilder.Options);
    }
}

With this factory, the CLI finds the DbContext directly:

1
2
3
4
5
# Now just point to the data project β€” no --startup-project
cd src/MeuEcommerce.Infra.Data.PostgreSQL

dotnet ef migrations add InitialCreate
dotnet ef database update

πŸ’‘ Tip: IDesignTimeDbContextFactory is used only by the EF Core CLI (at design time). At runtime, the DbContext is still resolved by the dependency injection configured in the IoC project. Both paths coexist without conflict.


dotnet user-secrets for Connection Strings

Never put connection strings with passwords in appsettings.json (which goes to Git). Use dotnet user-secrets to store sensitive data locally.

Initial Setup

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# In the project that has the IDesignTimeDbContextFactory (Infra.Data.PostgreSQL)
cd src/MeuEcommerce.Infra.Data.PostgreSQL
dotnet user-secrets init

# Set the connection string
dotnet user-secrets set "ConnectionStrings:DefaultConnection" \
  "Host=localhost;Port=5432;Database=meuecommerce;Username=postgres;Password=minha-senha-local"

# Check the stored secrets
dotnet user-secrets list

In the Api project (entry point), do the same:

1
2
3
4
5
cd src/MeuEcommerce.Api
dotnet user-secrets init

dotnet user-secrets set "ConnectionStrings:DefaultConnection" \
  "Host=localhost;Port=5432;Database=meuecommerce;Username=postgres;Password=minha-senha-local"

In appsettings.json β€” No Password

The appsettings.json versioned in Git stays free of sensitive data:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
{
  "ConnectionStrings": {
    "DefaultConnection": ""
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information"
    }
  }
}

At runtime, ASP.NET Core’s builder.Configuration loads user-secrets automatically when IsDevelopment() is true. In production, use environment variables or Azure Key Vault.

Running Migrations with Secrets

With IDesignTimeDbContextFactory configured to read AddUserSecrets, the EF Core CLI commands work directly:

1
2
3
4
5
6
7
8
cd src/MeuEcommerce.Infra.Data.PostgreSQL

# The factory reads the connection string from user-secrets
dotnet ef migrations add AdicionarTabelaProdutos
dotnet ef database update

# To see the SQL that will be generated (without running it):
dotnet ef migrations script --idempotent

⚠️ Warning: Each developer on the team must run dotnet user-secrets set on their own machine with the local database credentials. User-secrets are stored in %APPDATA%\Microsoft\UserSecrets\ (Windows) or ~/.microsoft/usersecrets/ (Linux/macOS) and never go to Git.


Scaffolding: Existing Database (Reverse Engineering)

When you need to integrate with an existing database (legacy), EF Core can automatically generate the entities and configurations from the existing schema. This is called scaffolding or reverse engineering.

Basic Command

1
2
3
4
5
6
7
8
dotnet ef dbcontext scaffold \
  "Host=localhost;Port=5432;Database=sistema_legado;Username=postgres;Password=senha" \
  Npgsql.EntityFrameworkCore.PostgreSQL \
  --project src/MeuEcommerce.Infra.Data.PostgreSQL \
  --output-dir Entities \
  --context-dir . \
  --context LegadoDbContext \
  --force

Essential Scaffold Options

ParameterDescription
--output-dir EntitiesWhere to generate the entity classes
--context-dir .Where to generate the DbContext
--context LegadoDbContextName of the DbContext class
--schema publicScaffold only the tables of a specific schema
--table produtos --table categoriasScaffold only specific tables
--no-onconfiguringDoesn’t generate OnConfiguring with the hardcoded connection string
--data-annotationsUses Data Annotations (the default is Fluent API β€” we want Fluent API!)
--forceOverwrites existing files
--no-pluralizeDoesn’t pluralize DbSet names

By default, scaffold already uses Fluent API (not Data Annotations). For maximum control:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
dotnet ef dbcontext scaffold \
  "Host=localhost;Port=5432;Database=sistema_legado;Username=postgres;Password=senha" \
  Npgsql.EntityFrameworkCore.PostgreSQL \
  --project src/MeuEcommerce.Infra.Data.PostgreSQL \
  --output-dir Entities/Legado \
  --context-dir . \
  --context LegadoDbContext \
  --no-onconfiguring \
  --no-pluralize \
  --force

πŸ’‘ Tip: After scaffolding, move the generated entities to the Domain project and adjust the namespaces. Scaffold generates everything in the data project, but following clean architecture, entities belong to the Domain. The Fluent API configurations stay in the data project.

Partial Scaffold (Specific Tables)

For large databases, scaffold only the tables you need:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
# Only tables from the 'vendas' schema
dotnet ef dbcontext scaffold \
  "Host=localhost;Database=legado;Username=postgres;Password=senha" \
  Npgsql.EntityFrameworkCore.PostgreSQL \
  --schema vendas \
  --project src/MeuEcommerce.Infra.Data.PostgreSQL \
  --output-dir Entities/Vendas \
  --context VendasDbContext \
  --no-onconfiguring

# Or specific tables
dotnet ef dbcontext scaffold \
  "Host=localhost;Database=legado;Username=postgres;Password=senha" \
  Npgsql.EntityFrameworkCore.PostgreSQL \
  --table produtos --table categorias --table pedidos \
  --project src/MeuEcommerce.Infra.Data.PostgreSQL \
  --output-dir Entities/Core \
  --context CoreLegadoDbContext \
  --no-onconfiguring

Providers for Scaffold

The provider in the scaffold command corresponds to the target database:

DatabaseNuGet Provider
PostgreSQLNpgsql.EntityFrameworkCore.PostgreSQL
SQL ServerMicrosoft.EntityFrameworkCore.SqlServer
OracleOracle.EntityFrameworkCore
MySQLPomelo.EntityFrameworkCore.MySql
SQLiteMicrosoft.EntityFrameworkCore.Sqlite

Managing Migrations in Teams with Multiple Developers

This is one of the biggest practical challenges of EF Core in enterprise projects. When 3, 5 or 10 developers create migrations at the same time, conflicts are inevitable if there is no clear process.

The Problem: Migration Conflicts

Imagine two developers working on separate branches:

1
2
3
4
5
main ─────────────── Migration_001 (InitialCreate)
  β”‚
  β”œβ”€β”€ feat/produtos ── Migration_002_AdicionarProdutos (Dev A)
  β”‚
  └── feat/pedidos ─── Migration_002_AdicionarPedidos  (Dev B)

Both migrations have the same snapshot as their base (after Migration_001). When Dev B merges after Dev A, EF Core detects that the snapshot is inconsistent and fails.

When there is a conflict, remove the conflicting migration and recreate it on top of the current state:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# Dev B after pull/merge of Dev A's branch:

# 1. Remove the conflicting migration (BEFORE applying it to the database)
dotnet ef migrations remove \
  --project src/MeuEcommerce.Infra.Data.PostgreSQL

# 2. Make sure the local database is up to date with Dev A's migrations
dotnet ef database update \
  --project src/MeuEcommerce.Infra.Data.PostgreSQL

# 3. Recreate the migration on top of the correct state
dotnet ef migrations add AdicionarPedidos \
  --project src/MeuEcommerce.Infra.Data.PostgreSQL

Strategy 2: Merging the Model Snapshot

The AppDbContextModelSnapshot.cs file is what causes most merge conflicts. Handle it like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
# In case of a snapshot conflict, ALWAYS:
# 1. Accept the version from the target branch (main/develop)
git checkout --theirs src/MeuEcommerce.Infra.Data.PostgreSQL/Migrations/AppDbContextModelSnapshot.cs

# 2. Remove your migration
dotnet ef migrations remove --project src/MeuEcommerce.Infra.Data.PostgreSQL

# 3. Update the local database
dotnet ef database update --project src/MeuEcommerce.Infra.Data.PostgreSQL

# 4. Recreate your migration with the correct snapshot as its base
dotnet ef migrations add SuaMigration --project src/MeuEcommerce.Infra.Data.PostgreSQL

Strategy 3: Naming Convention with Timestamp

Use migration names with a timestamp to avoid collisions:

1
2
3
4
5
6
7
8
# Instead of generic names that can collide:
dotnet ef migrations add 20260118_AdicionarTabelaPedidos

# Recommended format: YYYYMMDD_MigrationName
# Examples:
dotnet ef migrations add 20260118_AdicionarPedidos
dotnet ef migrations add 20260119_AlterarProdutoSku
dotnet ef migrations add 20260120_CriarIndiceProdutoNome

Golden Rules for the Team

  1. Never edit a migration already applied to the production/staging database β€” create a new migration to fix it.

  2. Merge main into your branch BEFORE creating the migration β€” this guarantees the snapshot is up to date.

  3. One feature, one migration β€” avoid multiple migrations per PR. If you need adjustments, remove it, adjust the entity and recreate it.

  4. Review migrations in the Pull Request β€” the generated SQL (dotnet ef migrations script) must be reviewed like any other code.

  5. Keep the snapshot in Git β€” AppDbContextModelSnapshot.cs MUST be versioned. Never add it to .gitignore.

  6. Use --idempotent for production scripts β€” it generates SQL with IF NOT EXISTS, safe to run multiple times:

1
2
3
dotnet ef migrations script --idempotent \
  --project src/MeuEcommerce.Infra.Data.PostgreSQL \
  --output migration-producao.sql
  1. Communicate in the team channel before creating migrations β€” a simple message like “I’m going to create a migration for table X” avoids duplicated work.

⚠️ Warning: In larger teams (8+ devs), consider designating an integration branch where all migrations are consolidated before going to main. This drastically reduces snapshot conflicts.


Complete Flow: From the Entity to the Database

Complete EF Core Migrations flow diagram showing the steps from the entity change, Fluent API configuration and migration creation to the PostgreSQL database update

To consolidate everything, here is the complete flow in a multi-layer project:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 1. Create/edit the entity in Domain (no reference to EF Core)
# src/MeuEcommerce.Domain/Entities/Pedido.cs

# 2. Create the Fluent API configuration in Infra.Data
# src/MeuEcommerce.Infra.Data.PostgreSQL/Configurations/PedidoConfiguration.cs

# 3. Add the DbSet to AppDbContext
# public DbSet<Pedido> Pedidos => Set<Pedido>();

# 4. Register it in IoC (if needed β€” repository, etc.)

# 5. Make sure you are on the up-to-date branch
git pull origin main

# 6. Create the migration
cd src/MeuEcommerce.Infra.Data.PostgreSQL
dotnet ef migrations add 20260118_AdicionarPedidos

# 7. Check the SQL that will be generated
dotnet ef migrations script --idempotent

# 8. Apply it to the local database
dotnet ef database update

# 9. Test the application

# 10. Commit and PR
git add .
git commit -m "feat(domain): add Pedido entity with Fluent API"

Essential Reference Commands

ActionCommand
Create migrationdotnet ef migrations add Nome --project Infra.Data
Apply migrationsdotnet ef database update --project Infra.Data
Remove last migrationdotnet ef migrations remove --project Infra.Data
List migrationsdotnet ef migrations list --project Infra.Data
Generate SQL scriptdotnet ef migrations script --idempotent --project Infra.Data
Script between migrationsdotnet ef migrations script MigA MigB --project Infra.Data
Revert migrationdotnet ef database update NomeMigAnterior --project Infra.Data
Scaffold existing databasedotnet ef dbcontext scaffold "connstr" Provider --project Infra.Data
Check pendingdotnet ef migrations list --project Infra.Data (shows Pending)

Tips and Good Practices

  1. Always generate the SQL script before applying to production β€” never use dotnet ef database update directly in production. Generate it with --idempotent, review it and apply it via the DBA or a pipeline.

  2. Use IDesignTimeDbContextFactory β€” it removes the dependency on the startup project and lets each developer use their own secrets.

  3. Separate migrations per provider β€” if your application supports PostgreSQL and SQL Server, keep separate migrations with MigrationsAssembly() pointing to different projects.

  4. Don’t ignore the snapshot β€” AppDbContextModelSnapshot.cs is the “current state” of the model for the EF Core CLI. Without it, the CLI can’t compute the diff for the next migration.

  5. Automate with a Makefile or scripts β€” create shortcuts for the most used commands. To learn more about automation with Makefile, see Makefile: Automating tasks for Python, Hugo and Docker.

  6. Review the generated SQL in PRs β€” add the output of dotnet ef migrations script as a comment on the PR so the team can review the DDL.

  7. Use HasData() with caution β€” seed data via HasData() generates migrations. For large or dynamic data, prefer separate SQL scripts.

  8. Configure retry for database update β€” in CI/CD, the database may not be ready yet. Use:

1
2
3
4
5
6
7
optionsBuilder.UseNpgsql(connectionString, npgsql =>
{
    npgsql.EnableRetryOnFailure(
        maxRetryCount: 5,
        maxRetryDelay: TimeSpan.FromSeconds(30),
        errorCodesToAdd: null);
});

Conclusion

Managing EF Core Migrations in multi-layer projects requires specific configuration, but the reward is an organized, secure and sustainable codebase. IDesignTimeDbContextFactory solves the design-time problem in solutions with multiple csproj files. dotnet user-secrets keeps connection strings out of versioned code. Scaffolding lets you integrate legacy databases without rewriting the schema by hand. And with clear naming conventions, migration rebasing and communication within the team, it is possible to scale to large teams without constant conflicts.

The EF Core CLI is powerful, but it demands discipline. Establish the team rules from the start of the project, document the migration creation flow in the README, and review the generated SQL in every Pull Request. To understand how advanced Fluent API mapping generates these migrations correctly, check out EF Core 8 Fluent API: Mapping, ORM and Decoupling.


Read Also


References