我正在将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在运行时迁移
发布评论