【问题标题】:Why I get error on update-database command?为什么我在 update-database 命令上出现错误?
【发布时间】:2016-09-01 09:21:48
【问题描述】:

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

这里是实体:

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

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

【问题讨论】:

    标签: entity-framework-6 code-first


    【解决方案1】:

    这可能是因为事实上您已经有了ClientTypeId 列(因为在迁移时我们没有CreateColumn 操作)并且您可能在该列中有一些非空值。当您创建新的(空)表ClientTypes 并将FK 设置为此表时,客户端表在刚刚创建的新表中没有主体(父行),结果 - 抛出异常。因此,您应该在创建FK 之前清除列ClientTypeId,然后根据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");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 2017-04-24
      • 1970-01-01
      • 2021-06-21
      • 2019-09-13
      • 2019-11-10
      • 1970-01-01
      相关资源
      最近更新 更多