gpt4 book ai didi

c# - 在 MySql.Data.EntityFrameworkCore 中找不到 Database SetInitializer

转载 作者:行者123 更新时间:2023-11-29 15:36:23 26 4
gpt4 key购买 nike

我正在使用MySql.Data.EntityFrameworkCore连接mysql的提供者。现在我想在使用 DropCreateDatabaseAlways 初始化数据库时播种数据,但是当我尝试这样使用时却找不到

Database.SetInitializer<SmContext>(new SMDbInitializer<SmContext>());

还有我的SMDbInitializer看起来像这样。

private class SMDbInitializer<T> : DropCreateDatabaseAlways<SmContext> 
{

protected override void Seed(SmContext context)
{

//Some code
base.Seed(context);
}
}

最佳答案

您可以创建一个 DbInitializer.cs 并调用 dbContext.Database.EnsureDeleted() ;删除现有数据库。

public static class DbInitializer
{
public static void Initialize(MyDbContext context)
{
//Ensures that the database for the context does not exist. If it does not exist, no action is taken.
//If it does exist then the database is deleted.
//Warning: The entire database is deleted an no effort is made to remove just the database objects that are used by the model for this context.
context.Database.EnsureDeleted();

//create the database
context.Database.EnsureCreated();

// Look for any students.
if (context.Students.Any())
{
return; // DB has been seeded
}

var students = new Student[]
{
new Student{FirstMidName="Carson",LastName="Alexander",EnrollmentDate=DateTime.Parse("2005-09-01")},
new Student{FirstMidName="Meredith",LastName="Alonso",EnrollmentDate=DateTime.Parse("2002-09-01")},
new Student{FirstMidName="Arturo",LastName="Anand",EnrollmentDate=DateTime.Parse("2003-09-01")},
new Student{FirstMidName="Gytis",LastName="Barzdukas",EnrollmentDate=DateTime.Parse("2002-09-01")},

};
foreach (Student s in students)
{
context.Students.Add(s);
}
context.SaveChanges();

//Applies any pending migrations for the context to the database.Will create the database if it does not already exist.
//Note that this API is mutually exclusive with DbContext.Database.EnsureCreated().
//EnsureCreated does not use migrations to create the database and therefore the
//database that is created cannot be later updated using migrations.
context.Database.Migrate();
}
}

在 Program.cs 中,修改 Main 方法以在应用程序启动时执行以下操作:

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<SchoolContext>();
DbInitializer.Initialize(context);
}
catch (Exception ex)
{
var logger = services.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "An error occurred while seeding the database.");
}
}

host.Run();
}

关于c# - 在 MySql.Data.EntityFrameworkCore 中找不到 Database SetInitializer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58207053/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com