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);
}
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 ?