How can I build the logic from the supplied logic in a LINQ-to-Entities Where expression?

In LINQ for Entity Framework, I often see a pattern in which I add a sentence .Whereif a string value is specified, for example:

IQueryable<Foo> query = Foos.AsQueryable()
if (!string.IsNullOrWhitespace(nameFilter)) query = query.Where(x => x.Name == name);
if (!string.IsNullOrWhitespace(addressFilter) != null) query = query.Where(x => x.Address == addressFilter );
if (!string.IsNullOrWhitespace(cityFilter) != null) query = query.Where(x => x.City == cityFilter );
// ...

I wanted to clear this and not repeat the filter. I thought I could create an extension method:

public static IQueryable<T> WhereEqualIfSpecified<T>(
    this IQueryable<T> query,
    Expression<Func<T, string>> fieldDelegate,
    string filterValue)
{
    return string.IsNullOrWhiteSpace(filterValue) 
        ? query 
        : query.Where(x => fieldDelegate(x) == filterValue);  // not valid, see question below
}

So that instead I can change my code to:

IQueryable<Foo> query = Foos.AsQueryable()
    .WhereEqualIfSpecified(x => x.Name, nameFilter)
    .WhereEqualIfSpecified(x => x.Address, addressFilter)
    .WhereEqualIfSpecified(x => x.City, cityFilter)
    // ...
;

But I found that in the method WhereEqualIfSpecifiedabove, it fieldDelegatemust be compiled into Func(), which should be called against the source of the entity, which destroys the point of execution of these steps, which will be executed in the database in my source code.

, Expression fieldDelegate, , . ? Expression WhereEqualIfSpecified, LINQ-to-Entities ?

0
1

, , - . , , . - , . Compose, :

public static IQueryable<T> WhereEqualIfSpecified<T>(
    this IQueryable<T> query,
    Expression<Func<T, string>> fieldExpression,
    string filterValue)
{
    return string.IsNullOrWhiteSpace(filterValue) 
        ? query 
        : query.Where(fieldExpression.Compose(value => value == filterValue);
}
+2

All Articles