如何在LINQ中包含父对象的字段?

时间:2013-08-04 10:33:24

标签: c# linq linq-to-entities

我正在尝试在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'.

1 个答案:

答案 0 :(得分:3)

您必须Include导航属性,而不是ID:

.Include(x => x.Problem.SubTopic)

如果我是你,我会考虑从数据库中获取你真正需要的而不是返回一个映射对象,以减轻负担。你必须相当肯定你不会遇到某个地方的N + 1问题...... :)