在EF Core中解析循环或多个级联路径?

时间:2020-09-05 21:03:11

标签: entity-framework-core foreign-keys ef-code-first

我在EF Core中遇到了与球体和多个层叠路径有关的问题。

介绍外键约束'FK_Approvals_Requests_RequestId' 表“批准”上的内容可能会导致循环或多个级联路径。
指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他 外键约束。无法创建约束或索引。看到 以前的错误。

这是我的实体:

CustomUser:

public class CustomUser
{
    [Key]
    [Required]
    public int Id { get; set; } // Primary key

    public List<Request> Requests { get; set; } // Collection of Request associated with the user

    public List<Approval> Approvals { get; set; } // Collection of Approvals associated with the user
}

请求:

public class Request
{
    [Key]
    [Required]
    public int Id { get; set; } // Primary key

    [Required]
    public CustomUser CustomUser { get; set; } // Optional inverse navigation property

    [ForeignKey("CustomUser")]
    public int CustomUserId { get; set; } // Foreign key

    [Required]
    public Approval Approval { get; set; } // Optional inverse navigation property

    [ForeignKey("Approval")]
    public int? ApprovalId { get; set; } // Foreign key
}

批准:

public class Approval
{
    [Key]
    [Required]
    public int Id { get; set; } // Primary key

    [Required]
    public CustomUser CustomUser { get; set; } // Optional inverse navigation property

    [ForeignKey("CustomUser")]
    public int CustomUserId { get; set; } // Foreign key

    [Required]
    public Request Request { get; set; } // Optional inverse navigation property

    [ForeignKey("Request")]
    public int? RequestId { get; set; } // Foreign key
}

在使用代码优先解决方案时如何防止此错误?我看了一些类似this one的答案,该答案似乎类似于通过Fluent API进行配置(显然无法通过属性进行配置),但某些方法如.WillCascadeOnDelete()不再可用。这些可能已被删除。

我的目标是:

  • 为用户提供批准和请求列表。
  • 请求可选地与批准相关联。
  • 批准总是 与请求相关。
  • 删除批准或请求不会删除父级用户。

到目前为止,解决该错误的唯一方法是手动编辑运行Add-Migration后创建的迁移文件。有一个onDelete参数,我可以将外键设置为ReferentialAction.NoAction。即使迁移文件打算在源代码控制中使用,这似乎是一个很差的解决方案,我希望通过Fluent API或属性对其进行配置。我如何实现我的目标?

0 个答案:

没有答案