从EF 5升级到6,新迁移交换列

时间:2014-09-23 19:21:51

标签: entity-framework ef-code-first entity-framework-5 entity-framework-6 ef-migrations

将代码优先项目从实体框架5升级到6.1.1时,具有2个外键到同一个表的模型会导致实体框架在未发生任何更改时检测到模式更改。

这是有问题的模型。

public class UserActivity : Activity
{
    public string UserMessage { get; set; }

    public int? OriginatorId { get; set; }
    public int UserId { get; set; }

    public virtual User Originator { get; set; }
    public virtual User User { get; set; }

    public class Configuration : EntityTypeConfiguration<UserActivity>
    {
        public Configuration()
        {
            HasOptional(x => x.Originator).WithMany().HasForeignKey(x => x.OriginatorId).WillCascadeOnDelete(false);
            HasRequired(x => x.User).WithMany().HasForeignKey(x => x.UserId).WillCascadeOnDelete(false);
        }
    }
}

这是从程序包管理器控制台运行命令Add-Migration时生成的迁移。

public partial class EF6 : DbMigration
{
    public override void Up()
    {
        DropForeignKey("dbo.UserActivities", "UserId", "dbo.Users");
        RenameColumn(table: "dbo.UserActivities", name: "UserId", newName: "__mig_tmp__0");
        RenameColumn(table: "dbo.UserActivities", name: "OriginatorId", newName: "UserId");
        RenameColumn(table: "dbo.UserActivities", name: "__mig_tmp__0", newName: "OriginatorId");
        AlterColumn("dbo.UserActivities", "OriginatorId", c => c.Int());
        AlterColumn("dbo.UserActivities", "UserId", c => c.Int(nullable: false));
        AddForeignKey("dbo.UserActivities", "OriginatorId", "dbo.Users", "ID");
        AddForeignKey("dbo.UserActivities", "UserId", "dbo.Users", "ID");
    }

    public override void Down()
    {
        DropForeignKey("dbo.UserActivities", "UserId", "dbo.Users");
        DropForeignKey("dbo.UserActivities", "OriginatorId", "dbo.Users");
        AlterColumn("dbo.UserActivities", "UserId", c => c.Int());
        AlterColumn("dbo.UserActivities", "OriginatorId", c => c.Int(nullable: false));
        RenameColumn(table: "dbo.UserActivities", name: "OriginatorId", newName: "__mig_tmp__0");
        RenameColumn(table: "dbo.UserActivities", name: "UserId", newName: "OriginatorId");
        RenameColumn(table: "dbo.UserActivities", name: "__mig_tmp__0", newName: "UserId");
        AddForeignKey("dbo.UserActivities", "UserId", "dbo.Users", "ID", cascadeDelete: true);
    }
}

EF 6.1.1中是否存在可以解释此行为的错误?看起来EF 6没有正确检测到2个外键。

作为一种解决方法,进行2次单独迁移,第一次删除外键,第二次迁移添加外键似乎解决了这个问题。

0 个答案:

没有答案