为什么我在更新数据库命令时出错?

Why I get error on update-database command?

我尝试使用代码优先的态度在两个表之间创建约束:

这是实体:

public class Client : IEntity
{
    public int Id { get; set; }
    public int IdentityNumber { get; set; }
    public int? ClientTypeId { get; set; }
    public string ClientName { get; set; }
    public string Departament { get; set; }
    public string Division { get; set; }

    public virtual ICollection<Contact> Contacts { get; set; }
    [ForeignKey("ClientTypeId")]
    public virtual ClientType ClientType { get; set; }
}

第二个实体:

public class ClientType : ILookupEntity
{
    public int Id { get; set; }
    public string Description { get; set; }
    public string Comment { get; set; } 
}

这是创建的迁移:

    public override void Up()
    {
        CreateTable(
            "dbo.ClientTypes",
            c => new
                {
                    Id = c.Int(nullable: false, identity: true),
                    Description = c.String(),
                    Comment = c.String(),
                })
            .PrimaryKey(t => t.Id);

        CreateIndex("dbo.Clients", "ClientTypeId");
        AddForeignKey("dbo.Clients", "ClientTypeId", "dbo.ClientTypes", "Id");
    }

    public override void Down()
    {
        DropForeignKey("dbo.Clients", "ClientTypeId", "dbo.ClientTypes");
        DropIndex("dbo.Clients", new[] { "ClientTypeId" });
        DropTable("dbo.ClientTypes");
    }
}

但是在更新数据库命令中我得到这个错误:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Clients_dbo.ClientTypes_ClientTypeId". The conflict occurred in database "Playground", table "dbo.ClientTypes", column 'Id'.

任何可能导致错误的原因?

这可能是因为您已经有列 ClientTypeId(因为在迁移时我们没有 CreateColumn 操作)并且您可能在此列中有一些非空值。当您创建新的(空)table ClientTypes 并将 FK 设置为此 table 客户端 table 在刚刚创建的新 [= =20=],结果 - 抛出异常。所以你应该在 FK 创建之前清除列 ClientTypeId 然后根据 ClientTypes table 内容填充它:

public override void Up()
{
    CreateTable(
        "dbo.ClientTypes",
        c => new
            {
                Id = c.Int(nullable: false, identity: true),
                Description = c.String(),
                Comment = c.String(),
            })
        .PrimaryKey(t => t.Id);

    CreateIndex("dbo.Clients", "ClientTypeId");

    //Add this line
    Sql("UPDATE dbo.Clients SET ClientTypeId = null")    
    AddForeignKey("dbo.Clients", "ClientTypeId", "dbo.ClientTypes", "Id");
}