Add migration with different assembly

后端 未结 14 1229
感情败类
感情败类 2020-12-02 14:25

I am working on a project with ASP.NET CORE 1.0.0 and I am using EntityFrameworkCore. I have separate assemblies and my project structure looks like this:

Pr         


        
14条回答
  •  天命终不由人
    2020-12-02 14:39

    This is for EF Core 3.x.

    Based on this answer from Ehsan Mirsaeedi and this comment from Ales Potocnik Hahonina, I managed to make Add-Migration work too.

    I use Identity Server 4 as a NuGet package and it has two DB contexts in the package. Here is the code for the class that implements the IDesignTimeDbContextFactory interface:

    public class PersistedGrantDbContextFactory : IDesignTimeDbContextFactory
    {
        public PersistedGrantDbContext CreateDbContext(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
    
            var dbContextBuilder = new DbContextOptionsBuilder();
    
            var connectionString = configuration.GetConnectionString("db");
    
            dbContextBuilder.UseSqlServer(connectionString, b => b.MigrationsAssembly("DataSeeder"));
    
            return new PersistedGrantDbContext(dbContextBuilder.Options, new OperationalStoreOptions() { ConfigureDbContext = b => b.UseSqlServer(connectionString) });
        }
    }
    

    Compared to the answer of Ehsan Mirsaeedi I modified these: I added the MigrationsAssembly:

    dbContextBuilder.UseSqlServer(connectionString, b => b.MigrationsAssembly("DataSeeder"));
    

    Where the "DataSeeder" is the name of my startup project for seeding and for migrations.

    I added an options object with ConfigureDbContext property set to the connection string:

    return new PersistedGrantDbContext(dbContextBuilder.Options, new OperationalStoreOptions() { ConfigureDbContext = b => b.UseSqlServer(connectionString) });
    

    It is now usable like this: 'Add-Migration -Context PersistedGrantDbContext

    At this point, when a migration has been created, one can create a service for this in a migration project having a method like this:

    public async Task DoFullMigrationAsync()
            {
                using (var scope = _serviceProvider.GetRequiredService().CreateScope())
                {
                    var persistedGrantDbContextFactory = new PersistedGrantDbContextFactory();
    
                    PersistedGrantDbContext persistedGrantDbContext = persistedGrantDbContextFactory.CreateDbContext(null);
                    await persistedGrantDbContext.Database.MigrateAsync();
    
                    // Additional migrations
                    ...
                }
            }
    

    I hope I helped someone.

    Cheers,

    Tom

提交回复
热议问题