Search code examples
entity-frameworklinq-to-entities

EF Core ignoring condition when extracted in method


After extracting a simple Linq2Entity condition on an IQueryable from

orders = orders.Where(o => o.AddressId.HasValue && _validAddressIds.Contains(o.AddressId.Value));

to a methode like so:

orders = orders.Where(o => IsValidAddress(o.AddressId));

...

private bool IsValidAddress(long addressId)
{
  return adressId.HasValue && _validAddressIds.Contains(addressId);
}

the condition is not contained in the generated SQL anymore, it gets applied in memory only. Why is that???


Solution

  • We have to use an expression like so:

    public Expression<Func<T, bool>> GetFilteredAddressExpression<T>() where T : IAddress
    {
        return x => x.AddressId != null && _validAddressIds.Contains(x.AddressId.Value);
    }