约束可能会导致循环或多个级联路径

问题描述 投票:0回答:1

它是这样的:

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约束。无法创建约束或索引。请参阅先前的错误。

我误解了多个级联路径的概念。

我不明白问题是什么,因为如果我们想删除经理,我们也希望他们的付款参与记录以及他们创建的发票都被删除。

您将如何在给定的架构中解决这个问题?

sql-server entity-framework foreign-keys ef-migrations
1个回答
0
投票

在必需(不可为空)的属性上创建外键关系时,默认情况下启用级联删除,请参见EF required relationship

这里的问题是您有2个从InvoicePaymentParticipantApplicationUser表的级联删除路径:

Path1: InvoicePaymentParticipant -> InvoicePayment -> Invoice -> ApplicationUser

Path2: InvoicePaymentParticipant -> ApplicationUser

这意味着,当您删除用户时,应删除以下记录:

路径1下的删除:

  1. 删除用户时,请删除其发票
  2. 删除发票时,请删除相应的发票付款
  3. 删除发票付款时,请删除相应的发票付款参与者

路径2下的删除:

  1. 删除用户时,请删除其发票付款参与者

这在Sql Server中是不允许的。有关更多信息,请参见this page

要解决该问题,您可以重新考虑表结构并删除从InvoicePaymentParticipantApplicationUser ...的外键路径之一

[另一种方法是更改​​外键的级联删除行为,您可以删除[Required]属性之一上的ManagerId属性,并且由于stringnullable类型,因此EF将设置key to null删除。

您也可以更改EF默认行为和turn off cascading delete

© www.soinside.com 2019 - 2024. All rights reserved.