You can use Predicatebuilder
1 - Create the following class:
public static class PredicateBuilder
{
public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; }
public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
}
public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
Expression<Func<T, bool>> expr2)
{
var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
return Expression.Lambda<Func<T, bool>>
(Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
}
}
2 - Use now as follows:
var query = db.Registros.AsQueryable();
var predicate = PredicateBuilder.False<SuaEntidade>();
if(model Paramter1)
{
predicate = predicate.And(x => x.Kind == MyEnum.Value2);
}
if(model Paramter2)
{
predicate = predicate.And(x => x.Kind == MyEnum.Value3);
}
var resultado = query.Where(predicate);
Speak man, this is Sopt, you can ask the questions in Portuguese
– Tmilitino
@But I’ve already translated :)
– Marcelo Dias
That is correct:
...WHERE KIND = 1 AND KIND = 2
? I don’t know if I’m forgetting anything but when you sayKind = 1 AND Kind = 2
will never return results, no? I didn’t meanKind = 1 OR Kind = 2
?– Livio Tonini