tik*_*ika 9 asp.net entity-framework entity-framework-core asp.net-core
我使用以下CLI进行数据库迁移:
dotnet ef migrations add <Name-of-Migration>dotnet ef database update但是,我正在寻找一种自动发生的方法:当检测到模型中的更改时.
到目前为止,我已经能够通过在Startup.cs中执行以下操作来消除步骤2:
private void SetupDatabase(IApplicationBuilder app)
{
using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
//Migate any pending changes:
context.Database.Migrate();
}
}
Run Code Online (Sandbox Code Playgroud)
这会迁移通过执行创建的任何挂起的更改:
dotnet ef migrations add <Name-of-Migration>
但它不会为模型中的任何更改添加迁移.我该如何自动化migrations add?
Has*_*san 11
更新:可以从代码中自动生成迁移的第一步,这是我个人不同意的设计决策.它仍然在你的目标EF7,因为我原来说不可能的(它已经从EF7删除它似乎提到这个SO发布以及对本博客文章由微软EF团队的一员伊万在评论中提到),但测试在Martin回复后的EF6中.第二步可以自动化,因为你已经发现,所以我不会再次重现它.
第一步的步骤如下(在带有EF6的ASP.net MVC Web应用程序中):
Enable-Migrations –EnableAutomaticMigrations.如果您的应用程序具有单个数据库上下文,则它也在那里应用了更改.public String TestField { get; set; }Add-Migration再次运行命令(希望,正如我在本答案的后面部分所指出的那样),您只需运行Update-Database并且应该更新数据库,以使您的应用程序正常运行.为什么自动模型更改监视自动生成和更新数据库可能会适得其反(在我的拙见和MSDN页面中):
上述内容可能并不适用于所有人,但我认为应该分享我同意不将迁移生成和应用程序自动化应用于DB的设计决策的原因.
考虑启用自动迁移的每个人都应该确保阅读MSDN页面以获取更多示例和缺点.
虽然我同意哈桑的答案,说明这可能非常棘手,但这个选项确实存在.
这是一个简短的简历:
enable-migrations -EnableAutomaticMigration:$ true
将自动生成Configuration类:
public Configuration()
{
AutomaticMigrationsEnabled = true;
//Set this parameter to true if you want to let auto-migration delete data when a property is removed from an entity.
//Not setting this will result in an exception when migration should remove a column.
AutomaticMigrationDataLossAllowed = true;
}
Run Code Online (Sandbox Code Playgroud)在Context类中设置DB Initializer
Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDBContext, MyConfigurationClass>("MyConnectionString"));
Run Code Online (Sandbox Code Playgroud)你去,改变你的模型,看看变化......
我仍然不确定我会使用它,因为当我这样说时我希望我的数据库改变...
| 归档时间: |
|
| 查看次数: |
1096 次 |
| 最近记录: |