它是这样的:
public class ApplicationUser : IdentityUser
{
// omitted for the sake of brevity...
public string LastName { get; set; }
public string FirstName { get; set; }
public string Email { get; set; }
}
public class Invoice
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Index(IsUnique = true)]
[Required]
public int No { get; set; }
[Required]
public DateTime Created { get; set; }
[Required]
public string ManagerId { get; set; }
public virtual ApplicationUser Manager { get; set; }
public virtual ICollection<InvoicePayment> Payments { get; set; }
}
public class InvoicePayment
{
[Key]
public Guid Id { get; set; }
[Required]
public int InvoiceId { get; set; }
public virtual Invoice Invoice { get; set; }
[Required]
public DateTime Created { get; set; }
[Required]
public decimal Total { get; set; }
public string Comment { get; set; }
public virtual ICollection<InvoicePaymentParticipant> Participants { get; set; }
}
public class InvoicePaymentParticipant
{
[Key]
public Guid Id { get; set; }
[Required]
public Guid InvoicePaymentId { get; set; }
public virtual InvoicePayment InvoicePayment { get; set; }
[Required]
public string ManagerId { get; set; }
public virtual ApplicationUser Manager { get; set; }
[Required]
public decimal Part { get; set; }
}
然后我尝试Update-Database
大喊:
在表'InvoicePaymentParticipants'上引入FOREIGN KEY约束'relationship_name'可能会导致>循环或多个级联路径。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他> FOREIGN KEY约束。无法创建约束或索引。请参阅先前的错误。
我误解了多个级联路径的概念。
我不明白问题是什么,因为如果我们想删除经理,我们也希望他们的付款参与记录以及他们创建的发票都被删除。
您将如何在给定的架构中解决这个问题?
在必需(不可为空)的属性上创建外键关系时,默认情况下启用级联删除,请参见EF required relationship
这里的问题是您有2个从InvoicePaymentParticipant
到ApplicationUser
表的级联删除路径:
Path1: InvoicePaymentParticipant -> InvoicePayment -> Invoice -> ApplicationUser
Path2: InvoicePaymentParticipant -> ApplicationUser
这意味着,当您删除用户时,应删除以下记录:
路径1下的删除:
路径2下的删除:
这在Sql Server中是不允许的。有关更多信息,请参见this page。
要解决该问题,您可以重新考虑表结构并删除从InvoicePaymentParticipant
到ApplicationUser
...的外键路径之一
[另一种方法是更改外键的级联删除行为,您可以删除[Required]
属性之一上的ManagerId
属性,并且由于string
是nullable
类型,因此EF将设置key to null删除。
您也可以更改EF默认行为和turn off cascading delete