本文介绍了在应用程序启动时使用Entity Framework核心运行数据库迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以将StartUp.cs
或project.json
配置为在应用程序启动时使用Entity Framework Core运行数据库迁移?
Is it possible to configure StartUp.cs
or project.json
to run database migrations using Entity Framework Core on application start?
现在我有执行此任务的中间件,但是它似乎对性能产生负面影响,因为正在检查每个收到的请求的数据库.
Now I have middleware that do this task, but it seems to make negative influence on performance because database is being checked each request received.
public class EntityFrameworkUpdateDatabaseMiddleware
{
private readonly RequestDelegate _next;
private readonly ApplicationDbContext _dbContext;
public EntityFrameworkUpdateDatabaseMiddleware(RequestDelegate next, ApplicationDbContext dbContext)
{
_next = next;
_dbContext = dbContext;
}
public async Task Invoke(HttpContext context)
{
await _dbContext.Database.MigrateAsync();
await _next.Invoke(context);
}
}
推荐答案
您可以在Startup.cs
中的config方法中执行此操作.最简单的方法是这样的:
You can do this in the config methods in your Startup.cs
. The simplest way is like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>();
// add other services
}
public void Configure(IApplicationBuilder app, ApplicationDbContext db)
{
db.Database.Migrate();
// configure other services
}
这篇关于在应用程序启动时使用Entity Framework核心运行数据库迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!