如何在 "Include" 中使用 "Where" 并在 Entity Framework 中查询 "Select" 6

How to user "Where" in "Include" and "Select" query in Entity Framework 6

在我的数据库中,我有 3 table、ExamsExamPlacesAgentsExams table 中每个考试的 Id 是 ExamPlaces table 中的外键,每个考试的 Id Exam Place 是 Agents table 中的一个外键。我想 return 来自特定代理的所有检查。我试过 return 这样的考试:

return _db.Exams
            .Include(e => e.ExamPlaces.Select(a => a.Agents
                .Where(agent => agent.AgentId == supervisorId))).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. Parameter name: path

是否可以像我使用“Include”那样使用“Where”子句来检索数据?

欣赏

Include 不影响返回哪些记录。它支持预先加载指定的导航属性。本质上,这是一种表达方式,"Yes, I want some Exams, but I'll also use the corresponding ExamPlaces later on, so go ahead and get them from the database now to save time"。与Where无关。

在这种特殊情况下,Where 很难处理。这与包含无关。如果你真的想从 _db.Exams 开始并使用 Where,我认为你可以在 Where 之前的某个地方放置一个 Join 以使其工作。

但是,请反过来考虑查询。您已经有了想要的代理。该代理有一个 ExamPlaces 集合,每个 ExamPlaces 都有一个 Exam 集合。您只需要将它们展平到一个列表中即可。像这样的东西应该可以工作(没有检查语法错误):

return _db.Agents
        .Find(supervisorId)
        .ExamPlaces
        .SelectMany(p => p.Exams)
        .Include(e => e.ExamPlaces.Select(p => p.Agents))
        .ToList();

如您所见,EF 6 不支持在 Include 方法中进行过滤。

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

EF+ Query IncludeFilter(免费和开源)允许轻松过滤包含的实体。

要使用它,您只需将所有 "Include" 替换为 "IncludeFilter"。您此时还需要在每个级别上使用 IncludeFilter。

示例:

return _db.Exams
            .IncludeFilter(e => e.ExamPlaces)
            .IncludeFilter(e => e.ExamPlaces.Select(a => a.Agents
                .Where(agent => agent.AgentId == supervisorId))).ToList();