EntityFramework尝试创建指向同一个表的多个链接,FK Constraint错误
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了EntityFramework尝试创建指向同一个表的多个链接,FK Constraint错误相关的知识,希望对你有一定的参考价值。
我有一个名为DeliveryRequest的表和另一个名为Operator的表,表DeliveryRequest如下:
public class DeliveryRequest
{
public int ID { get; set; }
public DateTime Date { get; set; }
public string UserID { get; set; }
public string Waybill { get; set; }
public string Reference { get; set; }
public int SupplierID { get; set; }
public Supplier Supplier { get; set; }
//[ForeignKey("Operator")]
public int SenderID { get; set; }
public Operator Sender { get; set; }
//[ForeignKey("Operator")]
public int ReceiverID { get; set; }
public Operator Receiver { get; set; }
public string Origin { get; set; }
public string Destination { get; set; }
public int ServiceID { get; set; }
public Service Service { get; set; }
}
而表运算符如下:
public class Operator
{
public int ID { get; set; }
public string Company { get; set; }
public int ContactID { get; set; }
public Contact Contact { get; set; }
public int AddressID { get; set; }
public Address Address { get; set; }
}
所以问题是,当我尝试更新我的数据库时,我得到一个FK约束错误,如下所示:
在表'DeliveryRequests'上引入FOREIGN KEY约束'FK_dbo.DeliveryRequests_dbo.Operators_SenderID'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。无法创建约束或索引。查看以前的错误。
而之前的错误是一样的。如下:
System.Data.SqlClient.SqlException(0x80131904):在表'DeliveryRequests'上引入FOREIGN KEY约束'FK_dbo.DeliveryRequests_dbo.Operators_SenderID'可能会导致循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。
专注于发件人和接收者部分,我不是专家,但错误必须在那里大声笑
//[ForeignKey("Operator")]
public int SenderID { get; set; }
public Operator Sender { get; set; }
//[ForeignKey("Operator")]
public int ReceiverID { get; set; }
public Operator Receiver { get; set; }
看起来你正在使用Code First
方法。因此,请尝试为DeliveryRequests
关闭CascadeDelete:
modelBuilder.Entity<DeliveryRequests>()
.HasRequired(c => c.Operator )
.WithMany()
.WillCascadeOnDelete(false);
例如:
public class YourDBContext: DbContext
{
public YourDBContext(): base()
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<DeliveryRequests>()
.HasRequired(c => c.Operator )
.WithMany()
.WillCascadeOnDelete(false);
}
}
以上是关于EntityFramework尝试创建指向同一个表的多个链接,FK Constraint错误的主要内容,如果未能解决你的问题,请参考以下文章
Entityframework 6:如何将自定义类型映射到 SQL 表