我应该把 Database.EnsureCreated 放在哪里? [英] Where should I put Database.EnsureCreated?
问题描述
我有一个 Entity Framework Core + ASP.NET Core 应用程序,当我的应用程序启动时,我想确保创建了数据库,并且最终(一旦我进行了迁移)我想确保它们也运行.
I have an Entity Framework Core + ASP.NET Core application and when my application starts up I want to ensure that the database is created, and eventually (once I have migrations) I want to ensure that those are also run.
最初我将 Database.EnsureCreated()
放入我的 DbContext
的构造函数中,但是自从 DbContext
的一个新实例以来,每次有人点击我的应用程序时它似乎都会运行>DbContext 每次都会创建.
Initially I put Database.EnsureCreated()
into the constructor of my DbContext
but that appears to run every time someone hits my application since a new instance of the DbContext
is created each time.
我试图将它放入我的启动代码中,但我需要一个 DbContext
的实例来执行此操作,目前尚不清楚如何获得该实例.我正在配置 EF:
I tried to put it into my startup code, but I need an instance of my DbContext
to do that and it is unclear how exactly to get one. I am configuring EF as so:
serviceCollection.AddEntityFramework()
.AddSqlServer()
.AddDbContext<Models.MyContext>(options => options.UseSqlServer(...));
我没有看到从服务集合中获取 DbContext 实例的方法,也没有看到任何合适的单例可以将 DbContext 注入其中以便我可以进行一些一次性初始化.
I don't see a way to get an instance of the DbContext from the service collection, and I don't see any appropriate singleton to inject a DbContext into so I can do some one-time initialization.
那么,确保在每次应用程序运行时调用一次与我的 DbContext 相关的代码的最佳位置是什么?
So what is the best place to ensure some code related to my DbContext is called once per application run?
推荐答案
在撰写本文时,还没有一个正确"的地方可以在应用程序启动时运行代码以使其在请求范围内执行(请参阅
At the time of this writing, there is not a "correct" place to run code on application startup such that it executes within the request scope (see https://github.com/aspnet/Hosting/issues/373).
目前,解决方法是执行以下操作,但不适用于更复杂的多应用场景(参见 https://github.com/aspnet/EntityFramework/issues/3070#issuecomment-142752126)
For now, the workaround is to do the following, but it won't work in more complex multi-application scenarios (see 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();
}
}
}
这篇关于我应该把 Database.EnsureCreated 放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!