我在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
之后的表中。怎么了?
答案 0 :(得分:0)
当您更改模型或在 DbContext 中进行更改,然后使用OnModelCreating
和Add-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
,如果数据库中没有记录,则会将新记录再次保存在数据库中。