当应用程序第一次运行时,Entityframework Core 2.0 Migration将被执行?

时间:2017-11-30 10:43:52

标签: entity-framework-core asp.net-core-webapi

我想知道EF迁移是否会在没有运行update-database命令的情况下与种子数据一起执行?即。在不执行update-database命令的情况下,我可以看到在数据库中创建的所有表。

有任何问题或这是预期的行为吗?

我使用单独的方法来播种数据:

    public async Task SeedAsync(IServiceProvider serviceProvider)
    {
        //Based on EF team's example at https://github.com/aspnet/MusicStore/blob/dev/samples/MusicStore/Models/SampleData.cs
        using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var dbContext = serviceScope.ServiceProvider.GetService<WorkflowDBContext>();
            if(!dbContext.AllMigrationsApplied())
            {
                serviceScope.ServiceProvider.GetService<WorkflowDBContext>().Database.Migrate();
                if (!await dbContext.Alert.AnyAsync())
                {
                    await SeedData(dbContext);
                }
            }
        }
    }

public static class DbContextExtension
{
    public static bool AllMigrationsApplied(this WorkflowDBContext context)
    {
        var applied = context.GetService<IHistoryRepository>()
                             .GetAppliedMigrations()
                             .Select(m => m.MigrationId);

        var total = context.GetService<IMigrationsAssembly>()
                             .Migrations
                             .Select(m => m.Key);

        return !total.Except(applied).Any();
    }
}

由于

1 个答案:

答案 0 :(得分:0)

EF Core无法自动应用迁移。您的应用可能会在某处调用DbContext.Database.EnsureCreated()Migrate() ...