【发布时间】: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