Somashekhar
Somashekhar

Reputation: 513

How to simplify where condition in entity framework

I have 4 parameters and I need to check in if condition and give the where condition. How to write it in simple way

Example

var param1, param2, param3, param4;

If(param1 !=0 && param2==0 && param3==0 && param4==0)
{
  var query = from x in xx
             where x.y== param1
              select x;
             // where param2,param3, parma4 are 0
}
else If(param1 !=0 && param2 !=0 && param3==0 && param4==0)
{
 var query = from x in xx
             where x.y== param1 && x.z== param2
              select x;
             // where param3, parma4 are 0
}
else if .......

and so on

Upvotes: 0

Views: 116

Answers (1)

Bennor McCarthy
Bennor McCarthy

Reputation: 11675

You're probably looking for something like this:

var query = from x in xx
            where (param1 == 0 || x.y == param1)
                && (param2 == 0 || x.z == param2)
                && (param3 == 0 || x.a == param3)
                && (param4 == 0 || x.b == param4)
            select x;

The downside of that approach is you're passing redundant parameters to the database some of the time. A better approach would be:

var query = xx;
if(param1 != 0)
    query = query.Where(x => x.y == param1);
if(param2 != 0)
    query = query.Where(x => x.z == param2);
if(param3 != 0)
    query = query.Where(x => x.a == param3);
if(param4 != 0)
    query = query.Where(x => x.b == param4);

This is a bit more typing, but is going to send the smallest possible query to the database.

Upvotes: 2

Related Questions