问题描述
每个练习都有一个与之相关的人。
Each Excercise has a person associated with it.
每个练习都有一系列与之相关的参与。
Each Excercise has a Collection of Engagements associated with it.
每个参与有2人关联它。 我需要帮助Rowan。
Each Engagement has 2 people associated with it. I need help Rowan.
当我使用RelatedTo属性修饰SurveyPerson时,我得到了这个错误。
I am gettting this error when I decorate the SurveyPerson with a RelatedTo attribute.
参考关系将导致周期性不允许的引用。 [约束名称= Excercise_SurveyPerson]
The referential relationship will result in a cyclical reference that is not allowed. [ Constraint name = Excercise_SurveyPerson ]
namespace TPS.KLE.Data
{
public class KLE_DB : DbContext
{
public DbSet<Person> People { get; set; }
public DbSet<Excercise> Excercises { get; set; }
public DbSet<Engagement> Engagements { get; set; }
}
public class Excercise
{
public int ID { get; set; }
public string Name { get; set; }
public int InitalSiteSurveyPesonID { get; set; }
public virtual ICollection<Engagement> Engagements { get; set; }
//this attribute causes the cyclical reference error
//without the attribute, SurveyPerson is null
[RelatedTo(ForeignKey = "InitalSiteSurveyPesonID")]
public virtual Person SurveyPerson { get; set; }
}
public class Engagement
{
public int ID { get; set; }
public int ExcerciseID { get; set; }
public int OwnerID { get; set; }
public int TargetID { get; set; }
public virtual Excercise Excercise { get; set; }
public virtual Person Owner { get; set; }
public virtual Person Target { get; set; }
}
public class Person
{
public int ID { get; set; }
public string Fname { get; set; }
public string Lname { get; set; }
public virtual ICollection<Engagement> Engagements { get; set; }
}
}
推荐答案
问题是Code First默认配置所需关系的级联删除。在您的情况下,删除参与将导致通过参与级联删除人员 - >人与参与 - >练习 - > Person,SQL Server
不支持此功能。
The issue is that Code First configures cascade delete on required relationships by default. In your case deleting an Engagement would cause a cascade delete of Person through Engagement -> Person and Engagement -> Exercise -> Person, SQL Server does not support this.
您需要关闭其中一个级联删除,这里有一些Fluent API代码可以关闭练习 - >人级联删除;
You need to switch off one of the cascade deletes, here is some Fluent API code to switch off the Exercise -> Person cascade delete;
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Excercise>()
.HasRequired(e => e.SurveyPerson)
.WithMany()
.HasConstraint((e, p) => e.InitalSiteSurveyPesonID == p.ID)
.WillCascadeOnDelete(false);
}
~Rowan
这篇关于周期性参考问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!