gpt4 book ai didi

c# - 为什么 Entity Framework 中的子实体包含引用父实体的虚拟属性?

转载 作者:行者123 更新时间:2023-11-30 16:17:20 25 4
gpt4 key购买 nike

我有以下与 EF5 一起使用的类

 public class Question
{
public Question()
{
this.Answers = new List<Answer>();
}
public int QuestionId { get; set; }
...
...
public string Title { get; set; }
public virtual ICollection<Answer> Answers { get; set; }
}

public class Answer
{
public int AnswerId { get; set; }
public string Text { get; set; }
public int QuestionId { get; set; }
public virtual Question Question { get; set; }
}

谁能告诉我为什么需要这个属性:

public virtual Question Question { get; set; }

如果我从不打算进行自动延迟加载,但确实打算有时将该对象与 include 一起引入,那么我是否需要这样的虚拟属性:

        var questions = _questionsRepository.GetAll()
.Include(a => a.Answers);

我问的原因是因为当与 Web API 一起使用时,它会给我 json 的循环引用错误。

最佳答案

在不查看您的映射配置的情况下,我可能有一些假设,但我怀疑您正在使用 Independent Association 来定义实体之间的关联关系。

这是 Entity Framework 的一个特性,其中对象之间的关系被建模为引用,因此您实际上不需要外键属性出现在您的对象上;这确实意味着您的两个实体都需要定义导航属性,因此 Entity Framework 能够管理关联。在您的情况下,您需要在 Answers 实体上有一个 Question 属性。

在更高版本的 Entity Framework 中(我相信从 4 开始),您可以使用不同类型的关联“外键关联”,这将允许您使用外键属性形成关联,这应该允许您删除 Question 导航属性(可能对您有帮助,也可能不会)。

这里有一个更好的解释作为公认的答案:Code First: Independent associations vs. Foreign key associations?

就是说,如果您的关联工作正常,您的问题可能出在您随后如何使用您的实体/Web API(我不太了解,无法评论)。

祝你好运=D

关于c# - 为什么 Entity Framework 中的子实体包含引用父实体的虚拟属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17320604/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com