How to add AND parameters in EF query

Asked

Viewed 57 times

-2

My view sends 5 parameters bool

Based on these parameters as I add where and in my query?

My code is

var query = db.Registros.AsQueryable();

if(model Paramter1) 
{
   query = query.Where(x => x.Kind == MyEnum.Value1);
}

if(model Paramter2) 
{
   query = query.Where(x => x.Kind == MyEnum.Value2);
}

But it doesn’t work

I need it to be added AND every accepted condition

Something like that:

SELECT * FROM RECORDS
if(model.Paramter1) {
 SELECT* FROM RECORDS WHERE KIND = 1
}
if(model.Paramter2) {
 SELECT* FROM RECORDS WHERE KIND = 1 AND KIND = 2
}
  • Speak man, this is Sopt, you can ask the questions in Portuguese

  • @But I’ve already translated :)

  • 2

    That is correct: ...WHERE KIND = 1 AND KIND = 2 ? I don’t know if I’m forgetting anything but when you say Kind = 1 AND Kind = 2 will never return results, no? I didn’t mean Kind = 1 OR Kind = 2 ?

2 answers

1

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

0

query. Where(x => x.Kind == Myenum.Value1 || x.Kind == Myenum.Value1 )

|| for OR and if it was AND it would be &&

try and tell me

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.