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

The Include path expression must refer to a navigation property defined on the type.

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

产生错误

'The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.'

知道为什么会这样吗?

好的。结束于

 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 的评论

正如一些人评论的那样,您不能在 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();