使用Entity Framework Core在运行时迁移

编程入门 行业动态 更新时间:2024-10-24 16:22:57
本文介绍了使用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在运行时迁移

本文发布于:2023-11-14 00:52:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585773.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Entity   Framework   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!