【问题标题】:EF move migration to new projectEF 迁移到新项目
【发布时间】:2016-04-29 17:56:54
【问题描述】:
我正在重构一个项目,并希望将所有 EF 实体和代码优先迁移移至一个新项目。我将 _Migrations 表中的 ContextKey 重命名为新的命名空间。运行 Add-Migration 时,未检测到新更改(Up() 和 Down() 为空)。
但是当我删除 localdb 时,不会重新创建数据库(它在移动之前已经创建)。显然只有在移动之后创建的迁移才会运行(但它不应该)。
如何确保在创建新数据库时运行所有迁移(包括迁移前的迁移)?
--编辑--
没关系:(
我将现有的迁移拖放到新项目并重命名了migration.cs文件中的命名空间,但忘记了migration.Designer.cs背后的代码
【问题讨论】:
标签:
c#
entity-framework
entity-framework-6
entity-framework-migrations
【解决方案1】:
您可以更新 dbo._MigrationHistory 表中的所有 ContextKey 列值以匹配新命名空间,仅此而已。
对我来说,我将所有代码优先模型从 ASP.NET MVC 应用程序转移到外部类库以与其他项目共享。
以下步骤可能会有所帮助
- 检查 dbo._MigrationHistory 可以看到所有记录都有
与配置类的确切类匹配的相似值
MyApp.Migrations.Configuration
2.(测试步骤)从包管理器控制台运行更新数据库并选择新的类库,您将看到例如下面的错误
There is already an object named 'AspNetRoles' in the database.
- 更新 _MigrationHistory 表的 ContextKey 列中的所有记录以匹配新的命名空间
MyApp.Domain.Migrations.Configuration
【解决方案2】:
引用表 [__MigrationHistory] 包含一个 ContextKey 列。除非另有重视,否则它维护 DbContext 命名空间的成员资格。
您可以设置派生自 dbMigrationsConfiguration 的类,并在构造函数中设置 ContextKey 值。
public sealed class Configuration : DbMigrationsConfiguration<Your.Context>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
AutomaticMigrationDataLossAllowed = true;
ContextKey = "PreviousValue";
}
protected override void Seed(Your.Context context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}