使用Entity Framework Core在运行时迁移 [英] Migrating at runtime with Entity Framework Core

查看:44
本文介绍了使用Entity Framework Core在运行时迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将PHP/Illuminate应用程序移植到ASP.NET Core/EF Core.它的一部分包括一个类似Wordpress的安装过程,该过程要求提供数据库凭据,然后创建必要的表以使该应用程序正常运行.本质上,我想像在Illuminate的架构生成器中一样在运行时运行某种迁移.

I'm porting a PHP/Illuminate application to ASP.NET Core/EF Core. Part of it consists of a Wordpress-like install process that asks for database credentials and then creates the necessary tables for the app to function. Essentially, I want to run some sort of migration at runtime like I can with Illuminate's schema builder.

我找到了 Microsoft.EntityFrameworkCore的引用.迁移名称空间似乎与我想做的事情有关,但是我似乎找不到任何有关如何实际使用它的文档或最佳实践.我想我可以编写原始SQL查询并执行这些查询,但是我更愿意使用一个不错的,强类型的API.

I found the reference for the Microsoft.EntityFrameworkCore.Migrations namespace which seems related to what I want to do, but I can't seem to find any documentation or best practices on how to actually use it. I imagine I could write raw SQL queries and execute those, but I'd much rather work with a nice, strongly typed API if possible.

使用EF Core可以做到这一点吗?有人对如何做到这一点有任何建议吗?我目前正在使用柚子MySQL提供程序,如果有什么不同的话.

Is this possible with EF Core, and does anyone have some suggestions on how to do it? I'm currently using the Pomelo MySQL provider if that makes any difference.

推荐答案

假设您已经准备好迁移,则Startup类中的类似操作将达到目的:

Assuming you already have migrations prepared, something like this in your Startup class will do the trick:

public void ConfigureServices(IServiceCollection services)
{
    // Wire up whatever your equivalent DbContext class is here
    services.AddDbContext<ApplicationDbContext>();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    using (var scope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
    {
        scope.ServiceProvider.GetService<ApplicationDbContext>().Database.Migrate();
    }
}

这篇关于使用Entity Framework Core在运行时迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆