【问题标题】:Entityframework Core 2.0 Migration will get executed when application runs first time?Entityframework Core 2.0 迁移将在应用程序第一次运行时执行?
【发布时间】:2017-11-30 10:43:51
【问题描述】:

我想知道 EF 迁移是否会在不运行 update-database 命令的情况下与种子数据一起执行? IE。不执行 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();
    }
}

谢谢

【问题讨论】:

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


    【解决方案1】:

    EF Core 永远不会自动应用迁移。您的应用程序可能在某处调用 DbContext.Database.EnsureCreated()Migrate()...

    【讨论】:

    • 谢谢。我已经更新了问题并粘贴了我用来播种数据的代码。我所做的是对的还是有任何代码味道?
    猜你喜欢
    • 2021-06-04
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 2015-11-06
    • 2021-09-29
    • 2021-12-31
    • 1970-01-01
    • 2018-03-01
    相关资源
    最近更新 更多