Skip to content

How to resolve the circular dependency between migration and startup projects? #3152

Closed

Description

@qwertie

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.

Activity

  1. qwertie commented on Mar 12, 2021

    @qwertie
    Author

    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:

    2>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(4919,5): error MSB3030: Could not copy the file "C:\Dev\Scratchpad\EntityFramework\bin\Debug\net5.0\EntityFramework.deps.json" because it was not found.
    2>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(4919,5): error MSB3030: Could not copy the file "C:\Dev\Scratchpad\EntityFramework\bin\Debug\net5.0\EntityFramework.runtimeconfig.dev.json" because it was not found.
    2>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(4919,5): error MSB3030: Could not copy the file "C:\Dev\Scratchpad\EntityFramework\bin\Debug\net5.0\EntityFramework.runtimeconfig.json" because it was not found.
    2>Done building project "EFSqlServerMigrations.csproj" -- FAILED.
    

    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.0 folder (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; calling ExampleDbContext.Database.Migrate() causes System.IO.FileNotFoundException: 'Could not load file or assembly 'EFNpgsqlMigrations, Culture=neutral, PublicKeyToken=null'. The system cannot find the file specified.'.

  2. bricelam commented on Mar 12, 2021

    @bricelam
    Contributor

    This page definitely need a lot of improvement. See #933.

    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"?

    The startup project is explained in more detail here.

    But I added the following code to the migrations projects and it doesn't make any difference

    You also need to remove the reference to the migrations assembly. See #3152.

    However, at runtime the startup project is mysteriously unable to see [the migration assemblies]

    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.

  3. qwertie commented on Mar 14, 2021

    @qwertie
    Author

    The startup project is explained in more detail here.

    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?

    You also need to remove the reference to the migrations assembly

    There was never any reference to the migrations assembly, because such a reference would be circular.

    Correct. This strategy won't work at runtime.

    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?

  4. ajcvickers commented on Mar 16, 2021

    @ajcvickers
    Contributor

    Closing this as a duplicate of #933 where we are tracking improvements to these docs.

  5. dgxhubbard commented on Dec 9, 2021

    @dgxhubbard

    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" ).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions