使用带有模型或迁移的Entity Framework 3.0播种数据吗?

使用最新的ASP.NET Core 3和EF Core 3,我希望像以前版本的EF一样播种数据。我注意到在microsoft文档中,他们指向此代码作为如何播种的示例。

https://github.com/aspnet/EntityFramework.Docs/tree/master/samples/core/Modeling/DataSeeding/Migrations

它使用以下代码更新迁移:

        migrationBuilder.InsertData(
            table: "Posts",columns: new[] { "PostId","BlogId","Content","Title","AuthorName_First","AuthorName_Last" },values: new object[] { 1,1,"Test 1","First post","Andriy","Svyryd" });

        migrationBuilder.InsertData(
            table: "Posts",values: new object[] { 2,"Test 2","Second post","Diego","Vega" });

这对我来说似乎“不舒服”,因为我学会初始化所有数据和表的方法是删除迁移文件夹,然后重新创建数据库。如果我手动更新迁移,那么我将永远保持该迁移。

在EF Core 3中是否有更好的方式处理种子数据?也许使用dbContext或以某种方式将某些内容放入模型类本身中?

xiaomading 回答:使用带有模型或迁移的Entity Framework 3.0播种数据吗?

您可以在Program.cs中播种数据。就像以下。

public static async Task Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();

    using (var scope = host.Services.GetRequiredService<IServiceScopeFactory>().CreateScope())
    {
        await SeedData.EnsureSeedData(scope.ServiceProvider);
    }

    host.Run();
}

创建一个SeedData类,并在其中编写播种逻辑。

public static async Task EnsureSeedData(IServiceProvider provider)
{
    var dbContext = provider.GetRequiredService<MyDbContext>();
    await dbContext.Database.MigrateAsync();

    if(!await dbContext.MyTables.AnyAsync())
    {
        await dbContext.MyTables.AddAsync(new MyTable {})
        await dbContext.SaveChangesAsync();
    }
}
本文链接:https://www.f2er.com/3157408.html

大家都在问