2013-08-04 61 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問題... :)

相關問題