With EF Core 10 migrations in a CarRental.Migrations class library, what do MigrationsAssembly, --project, --startup-project and an IDesignTimeDbContextFactory each do?
answer
- default: the DbContext's own assembly
- target project receives the files
- startup project is built and run
- entry point runs until the host is built
- CreateDbContext(string[] args)
basics
~20 sMigrationsAssembly names the assembly holding migrations (by default the DbContext's). --project picks where dotnet ef writes files, --startup-project what it builds and runs; an IDesignTimeDbContextFactory there creates the context without running the web app's Program.cs.
solid answer
~50 sBy default EF Core looks for migrations in the assembly that declares the `DbContext`; moving them to `CarRental.Migrations` needs `UseNpgsql(cs, b => b.MigrationsAssembly("CarRental.Migrations"))` wherever the context is configured, or the tools report that the target project does not match the migrations assembly. `--project` is the target that receives generated files; `--startup-project` is what the tools build and execute to obtain a context, and it must reference `Microsoft.EntityFrameworkCore.Design`. To get the context the tools first use an `IDesignTimeDbContextFactory<RentalDbContext>` found in the startup assembly or the context's assembly; otherwise they run the app's entry point until the host is built and resolve the context from its services, then fall back to a parameterless constructor. Putting the factory in the migrations project and using it as both target and startup keeps web startup code out of design time. EF Core 10 also needs `--framework` for multi-targeted projects.
code
csharp · 15 linespublic sealed class RentalDbContextFactory : IDesignTimeDbContextFactory<RentalDbContext>
{
public RentalDbContext CreateDbContext(string[] args)
{
var connectionString = args.Length > 0
? args[0]
: "Host=localhost;Database=rental_dev;Username=rental";
var options = new DbContextOptionsBuilder<RentalDbContext>()
.UseNpgsql(connectionString, npgsql => npgsql.MigrationsAssembly("CarRental.Migrations"))
.Options;
return new RentalDbContext(options);
}
}go deeper
Know that dotnet ef needs a project to write into and a project to run, and that both default to the current directory.
Explain the design-time creation order: factory, application services from the built host, then a parameterless constructor, and what each requires.
Show you can lay out data, migrations and app projects without cycles, keep design-time configuration identical to runtime, and keep web startup side effects out of tooling.
Decide when separate migration assemblies pay off, such as several providers, platform-specific apps or several bounded contexts, and who owns each migration set.
## Why split migrations into their own project A **migrations assembly** is the assembly EF Core scans for `Migration` classes and the model snapshot. By default it is the assembly that declares the `DbContext`. Teams move migrations out when the context lives in a shared data library, when the app project is platform-specific (it needs a workload or native host the tools cannot run), or when they keep one migration set per database provider. A common layout for the car-rental API: | Project | Holds | References | |---|---|---| | `CarRental.Data` | `RentalDbContext`, entity classes | the EF Core provider | | `CarRental.Migrations` | migrations, snapshot, the design-time factory | `CarRental.Data`, the provider, `Microsoft.EntityFrameworkCore.Design` (`PrivateAssets` all) | | `CarRental.Api` | the web app | `CarRental.Data`, and `CarRental.Migrations` only if it applies or lists migrations at runtime | `CarRental.Data` must not reference `CarRental.Migrations`: the migrations project already references the data project, so that would be circular. ## MigrationsAssembly The runtime and the tools both need to know where migrations are: - `options.UseNpgsql(connectionString, npgsql => npgsql.MigrationsAssembly("CarRental.Migrations"))`; an overload takes an `Assembly`. - Without it, `dotnet ef migrations add --project CarRental.Migrations` stops: *Your target project 'CarRental.Migrations' doesn't match your migrations assembly 'CarRental.Data'. Either change your target project or change your migrations assembly.* - At runtime, `Migrate` and `GetPendingMigrations` find nothing unless the setting points at an assembly the app actually loads. ## --project and --startup-project | Option | Meaning | Default | |---|---|---| | `--project` / `-p` | the **target** project: where generated files go and whose migrations are listed | current directory | | `--startup-project` / `-s` | the project the tools **build and execute** to create the context | current directory | | `--context` / `-c` | which `DbContext` when several exist | the only one found | | `--framework` | which target framework of a multi-targeted project | required in EF Core 10 when `TargetFrameworks` is set | The startup project must reference `Microsoft.EntityFrameworkCore.Design`; otherwise the tools say it does not and stop. ## How the tools obtain a DbContext At design time the tools try, in order: 1. **An `IDesignTimeDbContextFactory<TContext>`** in the startup assembly or in the context's own assembly. When found, it is used instead of everything else; its `CreateDbContext(string[] args)` receives the arguments written after `--` on the command line. 2. **The application's service provider.** The tools look for a `BuildWebHost`, `CreateWebHostBuilder` or `CreateHostBuilder` method; with top-level statements they run the entry point, wait for the host to be built, take its services and abort the app with `HostAbortedException`. Code before `builder.Build()` runs; `app.Run()` never does. The context is resolved from DI, so `AddDbContext` must have registered it. 3. **A parameterless constructor**, typically with `OnConfiguring`. The tools set `ASPNETCORE_ENVIRONMENT` and `DOTNET_ENVIRONMENT` to `Development` when neither is set, so the web app's development settings are what a step-2 context sees. ## Why the factory belongs in the migrations project - Program.cs may call services that are unavailable on a build agent: a secret store, a message broker, or a configuration source needing credentials. - A platform-specific app cannot be executed by the tools at all. - The factory makes design time explicit: the provider, the `MigrationsAssembly` and a development connection string, optionally overridden by an argument. Keep its configuration identical to runtime, with the same provider, options and migrations assembly; otherwise migrations are scaffolded for a model the app does not use. Provider-specific options matter here too: on Npgsql, settings such as mapped PostgreSQL enums or the assumed server version change the model or the generated SQL, so a factory that omits them scaffolds different migrations from the ones the running app expects. ## Failures and what they mean - *Unable to create a 'DbContext' of type …*: the tools could not construct the context; the inner exception usually names a missing service, configuration value or connection string. - *More than one DbContext was found*: pass `--context`. - *The project targets multiple frameworks*: EF Core 10's tools need `--framework`. - *Your startup project … doesn't reference Microsoft.EntityFrameworkCore.Design*: the wrong startup project, or a missing package. Then use the migrations project as both target and startup: ```bash dotnet ef migrations add AddCarCategory \ --project src/CarRental.Migrations \ --startup-project src/CarRental.Migrations ```
- How do you pass a connection string to an IDesignTimeDbContextFactory from the command line?Write it after `--`: `dotnet ef migrations list --project src/CarRental.Migrations --startup-project src/CarRental.Migrations -- "Host=db;Database=rental"`. Everything after `--` is not parsed by `dotnet ef` and arrives in the factory's `CreateDbContext(string[] args)`, so the factory must check `args` and fall back to a development default.
- Does the web app have to reference the migrations project?Only if it loads migrations at runtime, for example by calling `Migrate`, `MigrateAsync` or `GetPendingMigrationsAsync`. If migrations reach the database only through a deployment artifact, the app needs the data project alone. The data project must never reference the migrations project, because that would be circular.
- MigrationsAssembly matters only to the dotnet ef tools, never at runtime.
- --project and --startup-project are two spellings of the same option.
- The data project should reference the migrations project so the context finds them.
- dotnet ef runs the whole web app, including app.Run, to read its services.
- An IDesignTimeDbContextFactory is used only when the app's services fail to build.
Assumes EF Core 10, whose dotnet ef stops with an error when a project sets TargetFrameworks and no --framework is given.