我的 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; }
}
最佳答案
您得到此信息是因为“国家/地区”有一个到“州”的链接,而“VendorDetails”有一个到“国家/地区”和“州”的链接。这在 VendorDetails 和 State 之间提供了多条路径 - 一条通过 Country,一条直接。
我将禁用从 VendorDetails 链接到状态的级联删除:
modelBuilder
.Entity<VendorDetails>()
.HasOptional(e => e.State)
.WithMany()
.WillCascadeOnDelete(false);
关于asp.net-mvc - 引入 FOREIGN KEY 约束可能会导致循环或多条级联路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29937651/