【发布时间】: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