周期性参考问题? [英] Cyclical Reference issue?

查看:66
本文介绍了周期性参考问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个练习都有一个与之相关的人。

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 { getset; }
        public DbSet<Excercise> Excercises { getset; }
        public DbSet<Engagement> Engagements { getset; }
    }

    public class Excercise
    {
        public int ID { getset; }
        public string Name { getset; }
        public int InitalSiteSurveyPesonID { getset; }

        public virtual ICollection<Engagement> Engagements { getset; }

        //this attribute causes the cyclical reference error
        //without the attribute, SurveyPerson is null
        [RelatedTo(ForeignKey = "InitalSiteSurveyPesonID")]
        public virtual Person SurveyPerson { getset; }
    }
    public class Engagement
    {

        public int ID { getset; }
        public int ExcerciseID { getset; }
        public int OwnerID { getset; }
        public int TargetID { getset; }

        public virtual Excercise Excercise { getset; }
        public virtual Person Owner { getset; }
        public virtual Person Target { getset; }
    }
    public class Person
    {
        public int ID { getset; }
        public string Fname { getset; }
        public string Lname { getset; }

        public virtual ICollection<Engagement> Engagements { getset; }
    }
}

 

推荐答案

Hi Te rrence,

Hi Terrence,

问题是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


这篇关于周期性参考问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆