Repository navigation
Description
By following the beginning of the instructions, I've created (1) a database console app and (2) two migration assemblies for PostgreSQL and SQLServer (which one is active depends on a config-file setting). As instructed, I had to create the two database-creation migrations in the console app, then I moved them to the migration project.
The instructions say to "add a reference to your migrations project from the startup project", and the error message of dotnet ef migrations add likewise says "Ensure it is referenced by the startup project", which leads me to my first question: what does "startup project" mean? After all, the migration tool does not invoke Main(), does it? So why does it care which project is the "startup project"?
In most cases, this instruction causes a circular dependency. All migrations must have a reference to the project with the DbContext-derived class, but the DbContext-derived class is usually in the startup project, so it cannot have a reference back to the migrations projects.
Yes, the guide says
If this causes a circular dependency, you can update the base output path of the migrations project instead:
But I added the following code to the migrations projects and it doesn't make any difference (the startup project is in the EntityFramework folder):
<PropertyGroup>
<BaseOutputPath>..\EntityFramework\bin\</BaseOutputPath>
</PropertyGroup>
I also tried variations such as
<BaseOutputPath>../EntityFramework/bin/$(Configuration)</BaseOutputPath>
<BaseOutputPath>C:\Dev\Scratchpad\EntityFramework\bin\</BaseOutputPath>
<BaseOutputPath>C:\Dev\Scratchpad\EntityFramework\bin\$(Configuration)</BaseOutputPath>
But these don't work.
For reference, here's the command I'm using to add a migration (in Package Manager Console):
PM> dotnet ef migrations add SecondMigration --startup-project EntityFramework --project EFNpgsqlMigrations
Could not load assembly 'EFNpgsqlMigrations'. Ensure it is referenced by the startup project 'EntityFramework'.
Here's the entry point:
class Program {
public static IConfigurationRoot Config = new ConfigurationBuilder()
.AddJsonFile($"appsettings.json", true, true).Build();
public static ILoggerFactory LoggerFactory = new LoggerFactory();
static void Main(string[] args) {
using (var context = new ExampleDbContext(Config, LoggerFactory)) {
context.Database.Migrate();
...
}
}
}And here's the DbContext:
public class ExampleDbContext : DbContext, IDesignTimeDbContextFactory<ExampleDbContext>
{
private readonly IConfigurationRoot _config;
private readonly ILoggerFactory _loggerFactory;
private readonly ILogger _logger;
public ExampleDbContext(IConfigurationRoot config, ILoggerFactory loggerFactory) : base()
=> (_config, _loggerFactory, _logger) = (config, loggerFactory, loggerFactory.CreateLogger(typeof(ExampleDbContext)));
public DbSet<Example> Examples { get; set; } = null!; // EF sets it via reflection
protected override void OnConfiguring(DbContextOptionsBuilder builder)
{
// Returns null on failure (which is undocumented)
var sqlite = _config.GetConnectionString("Sqlite");
var npgsql = _config.GetConnectionString("Npgsql");
var sqlServer = _config.GetConnectionString("SqlServer");
if (!string.IsNullOrEmpty(sqlite)) {
_logger.LogInformation("Using Sqlite database");
builder.UseSqlite(sqlite);
} else if (!string.IsNullOrEmpty(npgsql)) {
builder.UseNpgsql(npgsql, dbcob => dbcob.MigrationsAssembly("EFNpgsqlMigrations"));
_logger.LogInformation("Using Npgsql database");
} else if (!string.IsNullOrEmpty(sqlServer)) {
builder.UseSqlServer(sqlServer, dbcob => dbcob.MigrationsAssembly("EFSqlServerMigrations"));
_logger.LogInformation("Using SqlServer database");
} else
throw new Exception("No connection string was provided. " +
"Something like the following is expected in appsettings.json: " +
"{ \"ConnectionStrings\": { \"PostgreSQL\": \"Server=localhost;Port=5432;Database=...;User Id=...;Password=...;\" } }");
#if DEBUG
builder.UseLoggerFactory(_loggerFactory);
// This line causes parameter values to be logged:
builder.EnableSensitiveDataLogging();
#endif
base.OnConfiguring(builder);
}
protected override void OnModelCreating(ModelBuilder model)
{
model.HasDefaultSchema("public");
base.OnModelCreating(model);
}
// This is called by the "Add-Migration" tool in Package Manager Console
ExampleDbContext IDesignTimeDbContextFactory<ExampleDbContext>
.CreateDbContext(string[] args) => new ExampleDbContext();
// This is called by the "dotnet ef migrations add" command-line tool
public ExampleDbContext() : this(Program.Config, Program.LoggerFactory) { }
}And appsettings.json:
{
"ConnectionStrings": {
"PostgreSQL": "Server=localhost;Port=5432;Database=testing456;User Id=postgres;Password=pgPass;",
//"SQLServer": "Data Source=(localdb)\\SQLEXPRESS;Initial Catalog=testing456;Integrated Security=True;"
},
"AppSettings": { }
}
Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.
- ID: b545eeff-6c33-3cc0-09ce-a3ad342d7438
- Version Independent ID: 34bc1bac-7338-d8ab-390d-8c5e88a48c10
- Content: Using a Separate Migrations Project - EF Core
- Content Source: entity-framework/core/managing-schemas/migrations/projects.md
- Product: entity-framework
- Technology: entity-framework-core
- GitHub Login: @bricelam
- Microsoft Alias: avickers
Activity
qwertie commentedon Mar 12, 2021
Another problem I just noticed is a strange side effect of changing
<BaseOutputPath>. After changing it, doing a "Rebuild" in Visual Studio causes errors like the following:These errors happen only for a "Rebuild". A plain "Build" succeeds.
The migrations DLLs are being placed in the startup project's
bin\Debug\net5.0folder (which is another side effect of changing<BaseOutputPath>- rather, I guess this effect is the very purpose of<BaseOutputPath>, but the documentation to which this issue relates did not inform me of that). However, at runtime the startup project is mysteriously unable to see them; callingExampleDbContext.Database.Migrate()causesSystem.IO.FileNotFoundException: 'Could not load file or assembly 'EFNpgsqlMigrations, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.'.bricelam commentedon Mar 12, 2021
This page definitely need a lot of improvement. See #933.
The startup project is explained in more detail here.
You also need to remove the reference to the migrations assembly. See #3152.
Correct. This strategy won't work at runtime. The primary reason for doing this is that you don't want your migrations to be used by your app. Instead they're treated as design-time artifacts that are only used by
dotnet ef.qwertie commentedon Mar 14, 2021
That page doesn't say what will be done precisely. It says a dummy project might be needed, but it does not attempt to justify this "need". It's not invoking Main() right?
There was never any reference to the migrations assembly, because such a reference would be circular.
I don't follow. Why would you make a decision that
context.Database.Migrate()shall be supported if and only if my app supports fewer than two database providers?ajcvickers commentedon Mar 16, 2021
Closing this as a duplicate of #933 where we are tracking improvements to these docs.
dgxhubbard commentedon Dec 9, 2021
I think this issue should re-opened, trying to follow the docs which seem to assume that most people are running migrations from CLI command line, does not work for the case of context.Database.Migrate. I have done the separate solutions for our different providers and generated the migrations, only to find context.Migrate.Database cannot find the migrations assembly specified in UseMyProvider ( connStr, x => x.MigrationsAssembly ( "MyProviderMigrations" ).