Mic*_*ltu 8 c# asp.net entity-framework-core
我有一个Entity Framework Core + ASP.NET Core应用程序,当我的应用程序启动时,我想确保创建数据库,并最终(一旦我有迁移)我想确保它们也运行.
最初我放入Database.EnsureCreated()了我的构造函数,DbContext但是每次有人点击我的应用程序时都会运行,因为DbContext每次都会创建一个新的实例.
我试着把它放到我的启动代码中,但我需要一个我的实例DbContext才能做到这一点,目前还不清楚如何获得一个.我正在配置EF如下:
serviceCollection.AddEntityFramework()
.AddSqlServer()
.AddDbContext<Models.MyContext>(options => options.UseSqlServer(...));
Run Code Online (Sandbox Code Playgroud)
我没有看到从服务集合中获取DbContext实例的方法,我没有看到任何适当的单例来注入DbContext,所以我可以做一些一次性初始化.
那么确保一些与我的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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6350 次 |
| 最近记录: |