[英]EF Core conditional include
I have a company entity with a one to many relationship to order entities.我有一个与订单实体有一对多关系的公司实体。
An order can be anonymous, in which case the related company should not be loaded when querying the orders.订单可以是匿名的,在这种情况下,查询订单时不应加载相关公司。
The current format creates an IQueryable and then adds filters to it as follows:当前格式创建一个 IQueryable,然后向其中添加过滤器,如下所示:
IQueryable<Order> queryable = ...
...
if (includeCompany is not null and true)
{
queryable = queryable.Include(o => o.Company);
}
if (includeAddress is not null and true)
...
Can I condition the include to use the order's isAnonymous bool in a single query, as to only include the company entity for the orders that are not anonymous?我可以将包含条件设置为在单个查询中使用订单的 isAnonymous 布尔值,以便仅包含非匿名订单的公司实体吗?
Sadly, no.可悲的是没有。 Filtered
Include
can't be applied to reference navigation properties, only collections.筛选的
Include
不能应用于参考导航属性,仅适用于 collections。
You'll have to resort to an ugly work-around:您将不得不求助于一个丑陋的解决方法:
context.Orders.Select(o => new
{
o,
Company = o.Order.IsAnonymous
? null
: o.Company
})
.AsEnumerable()
.Select(x => x.o)
Now the non-anonymous orders will have Company
reference because EF populates them by relationship fixup .现在非匿名订单将具有
Company
引用,因为 EF 通过关系 fixup填充它们。
AsEnumerable
causes EF to build the entire anonymous type. AsEnumerable
导致 EF 构建整个匿名类型。 Without it, the final Select
is part of the expression and EF concludes that the companies can be ignored entirely because it doesn't "see" them in the end result.没有它,最终的
Select
是表达式的一部分,EF 得出结论,可以完全忽略这些公司,因为它不会在最终结果中“看到”它们。
sure, queryable = queryable.Include(o => o.Company).where(o => o.isAnonymous);
当然,
queryable = queryable.Include(o => o.Company).where(o => o.isAnonymous);
queryable is IQueryable ,You can add conditions And there was no access to the database. queryable 是IQueryable ,你可以添加条件并且没有访问数据库。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.