2017-08-03 31 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(); 
相关问题