2013-08-04 26 views
0

我想从我的LINQ查询中的对象父项添加一个字段,但它不工作。这里是我的课:如何在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'. 

回答

3

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

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

如果我是你,我是d考虑从数据库中取出确实需要,然后返回一个映射对象,以减轻负载。你必须相当确定你不会遇到N + 1问题... :)

相关问题