0

With the latest ASP.NET Core 3, and EF Core 3, I want to seed data as I've done in previous version of EF. I notice that in the Microsoft docs, they point at this code as an example of how to seed.

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

It updates the migration with code like this:

        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",
            columns: new[] { "PostId", "BlogId", "Content", "Title", "AuthorName_First", "AuthorName_Last" },
            values: new object[] { 2, 1, "Test 2", "Second post", "Diego", "Vega" });

This seems "uncomfortable" to me as the way I've learned to init all my data and tables is to remove my migrations folder and then recreate the database. If I manually update a migration, then I'm stuck keeping this migration forever.

Is there a better way to handle seeding data in EF Core 3? Maybe with dbContext or somehow putting something in the model class itself?

4

2 回答 2

1

您可以在 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();
    }
}
于 2019-11-06T04:29:03.753 回答
0

可能不是实际的,但对于历史: MS DOCS -> 数据播种

简而言之:在您的上下文类中,覆盖 OnModelCreating(ModelBuilder builder)

protected override void OnModelCreating(ModelBuilder builder)

并使用这样的收缩:

modelBuilder
  .Entity<MyEntityClass>()
     .HasData(new MyEntityClass 
         { 
            Field= 1,
            Fiekd2= "http://sample.com",
            FieldX= ...
         });
于 2021-12-07T04:39:18.867 回答