Include路径表达式必须引用在类型上定义的导航属性。

时间:2017-08-03 14:16:32

标签: c# entity-framework linq eager-loading

我的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();

产生错误

  

' Include路径表达式必须引用导航属性   在类型上定义。使用虚线路径进行参考导航   属性和集合导航的Select运算符   属性'

任何想法为什么会发生这种情况?

2 个答案:

答案 0 :(得分:3)

有些人评论说,你不能在Include中使用Where方法。

免责声明:我是该项目的所有者Entity Framework Plus

EF + Query 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();

答案 1 :(得分: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