Reputation: 1628
I have some linq query like
Expression<Func<sometable, bool>> whereClauseDynamic= t => true;
if (#somecondition)
whereClauseDynamic= t => t.ID == #somevalue;
var temp= (from tax in db.sometable
join x in db.y on #someid
where trans.Finished >= start
where trans.Finished <= end
where whereClauseDynamic
.................
This works fine if i use Entity Framework type syntax
(from t in db.sometable
.Where(t => t.Finished >= start)
.Where(whereClauseLocation)
.................
But throws a compilation error in 1st case
Error CS0029 Cannot implicitly convert type 'System.Linq.Expressions.Expression>' to 'bool'
Error CS1662 Cannot convert query expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
What am I missing?
Upvotes: 1
Views: 1147
Reputation: 30022
One dirty trick is to use a default (always true) Expression for every table in the query. And based on the condition you have, you change one (or more) of them to a real where clause. In your query, you apply them all by default.
Expression<Func<X, bool>> whereClauseDynamicX = t => true;
Expression<Func<Y, bool>> whereClauseDynamicY = t => true;
Expression<Func<Z, bool>> whereClauseDynamicZ = t => true;
Expression<Func<someTable, bool>> whereClauseDynamicSomeTable = t => true;
from tax in db.sometable.Where(whereClauseDynamicSomeTable )
join x in db.x.Where(whereClauseDynamicX) on #someid
/* Continue the query */
Build your query on the way with the conditions, meaning:
IQueryable<someTable> someTableQuery = db.sometable;
IQueryable<X> xQuery = db.x;
IQueryable<Y> yQuery = db.y;
IQueryable<Z> zQuery = db.z;
if(condition1)
someTableQuery = someTableQuery.Where(x=> /* some condition */)
//.
//.
//.
var query = from tax in someTableQuery
join x in xQuery
/* REST */
The above approaches have not negative effect of performance whatsoever, because the query is only executed when Enumerated (using a loop or other methods like ToList()
- ToArray()
)
Upvotes: 2