I have a generic repository to whom I pass an Expression<Func<TEntity, bool>> filter
. For example this expression looks like:
filterExpr = part =>
(filter.ProductId != null ? filter.ProductId == part.ProductId : true) &&
(filter.SerialNumber != null ? filter.SerialNumber == part.SerialNumber : true);
In the repository I call QueryableExtensions.FirstOrDefaultAsync(filterExpr)
on a DbSet that I've got from DbContext:
this.dbSet = context.Set<TEntity>()
// ....
IQueryable<TEntity> query = dbSet;
return query.FirstOrDefaultAsync(filter);
It works well if either ProductId
or SerialNumber
or both are defined. If all filter properties are null
, I would expect the expression to evaluate to true
and therefore FirstOrDefaultAsync
to return the first Element in the queried table. But instead EF core seems to try to load the whole table. My memory consumption goes up a couple of GB and then I receive a timeout.
When I perform a UnitTest using an InMemoryDatabase I get null
as result which is also not what I expect.
Edit: Here is the UnitTest as requested.
[Fact]
public void GetPartWithEmptyFilterTest()
{
var optionsBuilder = new DbContextOptionsBuilder<ProductStatusContext>();
optionsBuilder.UseInMemoryDatabase("GetPartWithEmptyFilterTest");
var context = new ProductStatusContext(optionsBuilder.Options);
var part = new Part { SerialNumber = "abcdef" };
context.Parts.Add(part);
context.SaveChanges();
var unitOfWork = new UnitOfWork(context);
var service = new PartService(unitOfWork, null, null);
service.GetPartAsync(new PartFilterResource()).Result.Should().Be(part);
}
Edit2: My current workaround is to test all filter Properties for a null
value and evaluate the filte only if at least on propery is different from null
private bool AllPropertiesNull(object obj)
{
return !obj.GetType().GetProperties().Any(propInfo => propInfo.GetValue(obj) != null);
}
And then:
if(filter != null && AllPropertiesNull(filter))
filterExp = part => true;
But I'd like to avoid this.