实体框架,自动应用迁移 [英] Entity Framework, Automatic apply Migrations
问题描述
我正在使用 AutomaticMigrationsEnabled = true
的实体框架代码优先方法:
I am using Entity Framework Code First approach with AutomaticMigrationsEnabled = true
:
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DbContext, MigrateDBConfiguration>());
//////////////////////////////////
public class MigrateDBConfiguration : System.Data.Entity.Migrations.DbMigrationsConfiguration<DbContext>
{
public MigrateDBConfiguration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
}
}
项目的第一次运行将创建数据库和表如预期的那样。通过添加或删除字段更改模型后,我运行了添加迁移
。生成了Migration类,但在运行项目后发生此异常:
The first run of the project creates the database and tables as expected. After changing my model by adding or dropping fields, I ran Add-Migration
. The Migration class was generated but after running the project this exception occurs:
在EntityFramework.dll中发生了类型为'System.InvalidOperationException'的异常。
An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
其他信息:自创建数据库以来,支持 DBContext上下文的模型已更改了
。
Additional information: The model backing the 'DBContext' context has changed since the database was created.
编辑:根据 arturo menchaca 我这样更改了代码:
Per the guidance in the answer of arturo menchaca I changed my code like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DBContext, MigrateDBConfiguration<DBContext>>());
...
更改后会发生此异常:
数据库中已经有一个名为 MyTable的对象。
There is already an object named 'MyTable' in the database.
如何应用数据库迁移?
推荐答案
最后,我找到了解决问题的方法。我在每个应用程序开始时都调用此方法:
Finally, I found a solution to my problem. I call this method in each application start :
public void InitializeDatabase(DataAccessManager context)
{
if (!context.Database.Exists() || !context.Database.CompatibleWithModel(false))
{
var configuration = new DbMigrationsConfiguration();
var migrator = new DbMigrator(configuration);
migrator.Configuration.TargetDatabase = new DbConnectionInfo(context.Database.Connection.ConnectionString, "System.Data.SqlClient");
var migrations = migrator.GetPendingMigrations();
if (migrations.Any())
{
var scriptor = new MigratorScriptingDecorator(migrator);
var script = scriptor.ScriptUpdate(null, migrations.Last());
if (!string.IsNullOrEmpty(script))
{
context.Database.ExecuteSqlCommand(script);
}
}
}
}
这篇关于实体框架,自动应用迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!