2017-08-03 70 views
1

我LINQ查詢包含路徑表達式必須引用該類型上定義的導航屬性。

model.Questions = db.Questions 
        .Where (x => x.CategoriesID == categoryId) 
        .Include (qc => qc.QuestionCounters.Where(x => x.MemberID == User.Identity.GetUserId())) 
        .Include (qf => qf.QuestionFavorites.Where(x => x.MemberId == User.Identity.GetUserId())) 
        .Include (qt => qt.QuestionTags) 
        .ToList(); 

產生錯誤

「包含路徑表達式必須引用的類型所限定的導航屬性 。使用虛線路徑作爲參考導航 屬性,並使用選擇運算符來收集導航 屬性。

任何想法爲什麼會發生這種情況?

+0

你不能使用包含來選擇數據。已經有很多帖子了。 – Equalsk

+0

@Equalsk有沒有其他的選擇?這一個怪胎我 – OrElse

+0

重複 - 請參閱此https://stackoverflow.com/questions/15980665/ef-lambda-the-include-path-expression-must-refer-to-a-navigation-property和此https:/ /stackoverflow.com/questions/38676029/the-include-path-expression-must-refer-to-a-navigation-property-defined-on-the-t。 – 2017-08-03 14:21:53

回答

0

好的。結束了與

IQueryable<HomeViewModel> test = db.Questions 
            .Where(x => x.CategoriesID == categoryId) 
            .Select(q => q.ToHomeViewModel(User.Identity.GetUserId())); 

public static HomeViewModel ToHomeViewModel(this Question q, string memberId) 
{ 
    return new HomeViewModel() 
    { 
     QuestionCounters = q.QuestionCounters.Where(x => x.MemberID == memberId), 
     QuestionFavorites = q.QuestionFavorites.Where(x => x.MemberId == memberId), 
     QuestionTags = q.QuestionTags 
    }; 
} 

如何需要include畢竟? ;)

感謝評論@jle

1

至於有些人評論說,你不能在包括使用Where方法。

免責聲明:我是這個項目的所有者Entity Framework Plus

EF +查詢IncludeFilter功能允許過濾相關實體。

model.Questions = db.Questions 
       .Where (x => x.CategoriesID == categoryId) 
       .IncludeFiler (qc => qc.QuestionCounters.Where(x => x.MemberID == User.Identity.GetUserId())) 
       .IncludeFiler (qf => qf.QuestionFavorites.Where(x => x.MemberId == User.Identity.GetUserId())) 
       .IncludeFiler (qt => qt.QuestionTags) 
       .ToList(); 

百科:EF+ Query IncludeFilter

解決方案#2

另一種技術是通過使用投影(這是我的圖書館引擎蓋下做)

bd.Questions 
    .Select(q = new { 
     Question = q, 
     QuestionCounters = q.QuestionCounters.Where(x => x.MemberID == memberId), 
     QuestionFavorites = q.QuestionFavorites.Where(x => x.MemberId == memberId), 
     QuestionTags = q.QuestionTags 
    }) 
    .ToList() 
    .Select(x => x.Question) 
    .ToList(); 
相關問題