ASP-启动时核心迁移EF核心SQL DB [英] ASP - Core Migrate EF Core SQL DB on Startup
问题描述
是否可以让我的ASP Core Web API确保使用EF Core将数据库迁移到最新迁移?我知道可以通过命令行完成此操作,但是我想以编程方式进行操作.
Is it possible to have my ASP Core Web API ensure the DB is migrated to the latest migration using EF Core? I know this can be done through the command line, but I want to do it programatically.
更新
根据Janshair Khan的回答,我想到了这个帮助器课程:
Based on the answer from Janshair Khan I came up with this helper class:
using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MyWebApi.Models;
namespace MyWebApi
{
public static class DataSeeder
{
public static void SeedData(this IApplicationBuilder app)
{
var context = app.ApplicationServices.GetService<MyContext>();
if (!context.Database.EnsureCreated())
context.Database.Migrate();
}
}
}
您可以像这样在Startup.cs
中的Configure
方法中调用此方法:
You can call this from the Configure
method in your Startup.cs
like this:
app.SeedData();
推荐答案
您可以使用
db.Database.EnsureCreated();
使您的数据库与当前模型保持最新.如果要启用迁移(如果怀疑有后续迁移),请使用
to get your db up to date with your current model. If you want to enable migrations (If subsequent migrations are suspected), then use
db.Database.Migrate();
,并随时间推移进行后续迁移.
and put your subsequent migrations over time.
这篇关于ASP-启动时核心迁移EF核心SQL DB的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!