如何在LINQ中包含父对象的字段
本文关键字:对象 字段 包含父 LINQ | 更新日期: 2023-09-27 18:26:12
我正试图在LINQ查询中添加对象父级的字段,但它不起作用。以下是我的课程:
public Problem()
{
this.Questions = new List<Question>();
}
public int ProblemId { get; set; }
public int SubTopicId { get; set; }
public string Text { get; set; }
public virtual SubTopic SubTopic { get; set; }
public virtual ICollection<Question> Questions { get; set; }
}
public class Question : AuditableTable
{
public int QuestionId { get; set; }
public int ProblemId { get; set; }
public virtual Problem Problem { get; set; }
public virtual QuestionStatus QuestionStatus { get; set; }
}
var questions = _questionsRepository
.GetAll()
.Include(q => q.Problem.SubTopicId)
.Include(q => q.Answers)
.ToList();
我得到这个错误:
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=A specified Include path is not valid.
The EntityType 'Models.Contexts.Problem' does not declare a navigation
property with the name 'SubTopicId'.
您必须Include
导航属性,而不是ID:
.Include(x => x.Problem.SubTopic)
如果我是你,我会考虑从数据库中获取真正需要的,并返回一个映射对象,以减轻负载。你必须相当确定你不会在某个地方遇到N+1问题…:)