为什么我在update-database命令上出错?

时间:2016-09-01 09:21:49

标签: entity-framework-6 code-first

我尝试使用代码第一态度来创建两个表之间的限制:

这是实体:

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");
    }
}

但是在update-database命令上我收到了这个错误:

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'.

可能导致错误的是什么?

1 个答案:

答案 0 :(得分:3)

可能是因为您已经有了列ClientTypeId(因为在迁移时我们没有CreateColumn操作),并且您可能在此列中有一些非空值。当您创建新的(空)表ClientTypes并将FK设置为此表时,Clients表在新创建的表中没有主体(父行),因此抛出异常。因此,您应该在ClientTypeId创建之前清除列FK,然后根据ClientTypes表格内容填写它:

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");
}