EF Core conditional include

Viewed 1057

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<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?

2 Answers

Sadly, no. Filtered Include can't be applied to reference navigation properties, only 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.

AsEnumerable causes EF to build the entire anonymous type. 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.

sure, 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.

Related