gpt4 book ai didi

c# - 我应该把 Database.EnsureCreated 放在哪里?

转载 作者:太空狗 更新时间:2023-10-29 18:31:17 25 4
gpt4 key购买 nike

我有一个 Entity Framework Core + ASP.NET Core 应用程序,当我的应用程序启动时,我想确保数据库已创建,并且最终(一旦我有迁移)我想确保这些也运行。

最初我将 Database.EnsureCreated() 放入我的 DbContext 的构造函数中,但是自从 的新实例以来,每次有人点击我的应用程序时它似乎都会运行>DbContext 每次都会创建。

我试图将它放入我的启动代码中,但我需要一个我的 DbContext 实例来执行此操作,目前尚不清楚如何获得一个实例。我正在这样配置 EF:

serviceCollection.AddEntityFramework()
.AddSqlServer()
.AddDbContext<Models.MyContext>(options => options.UseSqlServer(...));

我没有看到从服务集合中获取 DbContext 实例的方法,也没有看到任何合适的单例来将 DbContext 注入(inject)到其中,因此我可以进行一些一次性初始化。

那么什么是确保每次应用程序运行时调用一次与我的 DbContext 相关的代码的最佳位置?

最佳答案

在撰写本文时,没有一个“正确”的位置可以在应用程序启动时运行代码,使其在请求范围内执行(参见 https://github.com/aspnet/Hosting/issues/373)。

目前,解决方法是执行以下操作,但它不适用于更复杂的多应用场景(参见 https://github.com/aspnet/EntityFramework/issues/3070#issuecomment-142752126)

public class Startup
{
...

public void Configure(IApplicationBuilder applicationBuilder, ...)
{
...
// NOTE: this must go at the end of Configure
var serviceScopeFactory = applicationBuilder.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
using (var serviceScope = serviceScopeFactory.CreateScope())
{
var dbContext = serviceScope.ServiceProvider.GetService<MyDbContext>();
dbContext.Database.EnsureCreated();
}
}
}

关于c# - 我应该把 Database.EnsureCreated 放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36958318/

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