我有两个相关的实体:ActiveContract
和 BudgetSource
。我试图获取所有标记为 isActive = true
的 BudgetSource,以及所有关联的 ActiveContracts
(也标记为 isActive = true
) 。我累了:
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
然后我将其更改为将滤镜放入投影中:
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 开发人员选择放入其查询提供程序中的功能。相反,您被迫以某种方式投影出相关实体的集合来过滤它们,您不能使用 Include
来为您完成此操作。
关于c# - Entity Framework 包含一个条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24068758/