Entity Framework include with a condition
我有两个实体,它们是相关的,
1 2 3 4 5 6 7 8 9 10 | var d = budgetSourceRep.All.Where(x => x.isAcitve) .OrderBy(x => x.SourceName) .Include(z => z.ActiveContracts.Where(q => q.isActive)) .Select(y => new EditSelectItemViewModel { Id = y.Id, SourceName = y.SourceName, DisplayOnNew = y.DisplayOnNew, NumberOfTimesUsed = y.ActiveContracts.Count() }).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
然后我将其更改为将过滤器放入投影中:
1 2 3 4 5 6 7 8 9 10 | var d = budgetSourceRep.All.Where(x => x.isAcitve) .OrderBy(x => x.SourceName) .Include(z => z.ActiveContracts) .Select(y => new EditSelectItemViewModel { Id = y.Id, SourceName = y.SourceName, DisplayOnNew = y.DisplayOnNew, NumberOfTimesUsed = y.ActiveContracts.Count(a => a.isActive) }).ToList(); |
这行得通,但我假设它会进行第二次查询来做到这一点?如果是这样,有没有办法一次性完成。
that works, but i'm assuming it's going to make a second query to do that?
不,不是。您可以通过查看为该查询生成的 SQL 来亲自查看。
查询提供程序成功地将您的第一个查询转换为 SQL 在理论上的可能性范围内,但这样做是……很难。这根本不是 EF 的开发人员选择放入他们的查询提供程序的功能。相反,您被迫以某种方式投射出相关实体的集合以过滤它们,您不能使用