以下是一个示例数据填充类中填充类别表的方法:
public static class MyDataSeeder
{
public static void SeedCategories(DataContext context)
{
if (!context.Categories.Any())
{
var categories = new List
{
new Category { Name = "Category 1" },
new Category { Name = "Category 2" },
new Category { Name = "Category 3" },
};
context.Categories.AddRange(categories);
context.SaveChanges();
}
}
}
要在应用程序启动时填充类别表,请在Startup类的ConfigureServices方法中将数据填充类添加到依赖注入容器:
services.AddScoped();
在Startup类的Configure方法中调用数据填充类的类别填充方法:
using (var scope = app.ApplicationServices.CreateScope())
{
var seeder = scope.ServiceProvider.GetRequiredService();
seeder.SeedCategories(context);
}