I have this project set up with EF4 and I’m using LINQ to Entities to form queries.
I’m having some trouble with a query that involves lots of conditional where clauses and several left outer joins.
I have partially solved the conditional where clauses with the following extension method (which I found here).
public static IQueryable<TSource> WhereIf<TSource>(this IQueryable<TSource> source, bool condition, Expression<Func<TSource, bool>> predicate)
{
if (condition)
return source.Where(predicate);
else
return source;
}
The problem I have now is that LINQ to Entities doesn’t recognize the extension method when I use it on the joined tables.
Here’s a part of the query:
from p in context.Entities.OfType<Patient>()
.WhereIf(!string.IsNullOrEmpty(name), p => p.Name.Contains(name))
from c in context.Contacts
.Where(cp => cp.EntityID == p.EntityId).DefaultIfEmpty()
.WhereIf(timestamp != null, c => c.Timestamp > timestamp)
I say partially solved because it works just fine the first time (patient name) in this query, but the second time (timestamp) it gives me this error:
LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[x.Contact] WhereIf[Contact](System.Linq.IQueryable`1[x.Contact], Boolean, System.Linq.Expressions.Expression`1[System.Func`2[x.Contact,System.Boolean]])' method, and this method cannot be translated into a store expression.
So, I’m wondering if anyone know how I can fix this?
The problem is that EF is unable to recognize
WhereIfinside aSelectMany. Rewriting your query into method syntax yields something like this (query is incomplete):The problem is the last
WhereIf. You should be able to move it outside theSelectMany:You can inspect the resulting SQL to see if you get what you actually want by casting the query into
ObjectQueryand calling the methodToTraceString: