引入FOREIGN KEY约束可能会造成环路或多级联路径

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths

我的 MVC 项目中有以下实体(代码优先方法) 我想知道我收到以下错误的原因是什么

Introducing FOREIGN KEY constraint 'FK_dbo.VendorDetails_dbo.States_StateID' on table 'VendorDetails' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint. See previous errors.

我只是想知道哪些表正在获得多个级联路径,任何图表都会有效,我应该像这样使用流利的 API 编写什么: modelBuilder.Entity<...>() .HasRequired(...) .WithMany(...) .HasForeignKey(...) .WillCascadeOnDelete(false);

public class VendorDetails
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int VendorID { get; set; }        
    [MaxLength(60)]
    public string VendorName { get; set; }        

    public int VendorTypeID { get; set; }
    public int CountryID { get; set; }
    public int StateID { get; set; }        

    [NotMapped]
    public string CountryName { get; set; }
    [NotMapped]
    public string StateName { get; set; }
    [NotMapped]
    public string VendorTypeName { get; set; }

    public virtual Country Country { get; set; }
    public virtual State State { get; set; }
    public virtual VendorType VendorType { get; set; }
}

public class VendorType
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int VendorTypeID { get; set; }                

    public string VendorTypeName { get; set; }

    public virtual ICollection<VendorDetails> Vendors { get; set; }
 }


public class Country
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CountryID { get; set; }
    public string CountryName { get; set; }

    public virtual ICollection<State> States { get; set; }
}

public class State
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int StateID { get; set; }
    public string StateName { get; set; }

    public int CountryID { get; set; }
    public virtual Country Country { get; set; }
}

你得到这个是因为 Country 有一个 link 到 State,而 VendorDetails 有一个 link 到 Country 和 State。这在 VendorDetails 和 State 之间提供了多条路径 - 一条通过 Country,一条直接。

我会在 link 上禁用级联删除以从 VendorDetails 声明:

modelBuilder
    .Entity<VendorDetails>()
        .HasOptional(e => e.State)
        .WithMany()
        .WillCascadeOnDelete(false);

替代@Richard 的建议,在创建迁移时,它可能在约束部分中指定了 'onDelete'。

table.ForeignKey( name: "FK_ServiceRequest_User_DeletedById",
                  column: x => x.DeletedById,
                  principalTable: "User",
                  principalColumn: "Id",
                  onDelete: ReferentialAction.Cascade);

您可以简单地删除该部分的最后一行(前提是您的默认设置是不执行任何操作)。否则,专门将 onDelete 设置为 ReferentialAction.NoAction 具有相同的结果。

我个人更喜欢@Richard 的处理方式,因为它将 post 处理放在一个地方(上下文),这意味着当您寻找这样的东西时,您不必搜索可能是大量迁移的内容,但这是将迁移保持为 'self managing' 的替代方法。