EF Core 2.2.4和种子数据

时间:2020-08-24 20:33:27

标签: entity-framework entity-framework-core ef-core-2.2

我在DataContext上有以下代码:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.ApplyConfiguration<CollectionSite>(new CollectionSiteMap());
        modelBuilder.ApplyConfiguration<TestOrderAlcoholResult>(new TestOrderAlcoholResultMap());
        //.... other configurations

        modelBuilder.Entity<ButtonStyle>().HasData(new ButtonStyle()
        {
            Label = "Sharp edges",
            Style = "border-radius: 0",
            IsDefault = true,
            Id = 1
        });
        modelBuilder.Entity<ColorScheme>().HasData(new ColorScheme()
        {
            Primary = "#a21521",
            Secondary = "#fcf7f8",
            Text = "#ced3dc",
            Background = "#4e8097",
            Shade = "#90c2e6",
            IsDefault = true,
            Id = 1
        });
        //.... seed other data

        base.OnModelCreating(modelBuilder);
    }

,但是数据未添加到update-database之后的表中。怎么了?

1 个答案:

答案 0 :(得分:0)

当您更改模型或在 DbContext 中进行更改,然后使用OnModelCreatingAdd-Migration时调用update-database。 / p>

OnModelCreating并非每次使用update-database时都运行。

根据Microsoft documentation,这是使用种子数据

的更好方法
public static void Main(string[] args)
{
     var host = CreateWebHostBuilder(args).Build();

    using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        try
        {
            var context = services.GetRequiredService<DbContext>();
            DbInitializer.InitializeData(context);
        }
        catch (Exception ex)
        {
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occurred while seeding the database.");
        }
    }

    host.Run();
}
public static class DbInitializer
{
    public static void InitializeData(DbContext context)
    {
        context.Database.EnsureCreated();
        context.ButtonStyle.Add(new ButtonStyle()
        {
            Label = "Sharp edges",
            Style = "border-radius: 0",
            IsDefault = true,
            Id = 1
        });
        context.ColorScheme.Add(new ColorScheme()
        {
            Primary = "#a21521",
            Secondary = "#fcf7f8",
            Text = "#ced3dc",
            Background = "#4e8097",
            Shade = "#90c2e6",
            IsDefault = true,
            Id = 1
        });
        context.SaveChanges();
    }
}

在这种情况下,每次运行程序时都会检查InitializeData,如果数据库中没有记录,则会将新记录再次保存在数据库中。