Given a list of filter parameters in the form of:
public class filterParm
{
public int age { get; set; }
public string name { get; set; }
}
Where:
var parms = new List<filterParm>
{
new filterParm {age = 22, "phil"},
new filterParm {age = 19, "dave"},
new filterParm {age = 31, "nick"}
};
How do I write an expression which would result in the following SQL where clause (note the OR operators in bold:
WHERE (age = 22 AND name = "phil")
OR (age = 19 AND name = "dave")
OR (age = 31 AND name = "nick")
My current implementation results in each of the statements seperated by the AND operator:
private _dbSet<user> Users { get; set; }
public List<user> CustomFilter(List<filterParm> parms)
{
IQueryable<TEntity> query = _dbSet;
if (parms.Count > 0 )
{
foreach (var parm in parms)
{
query = query.Where(u => u.Age == parm.Age && u.Name == parm.Name);
}
}
return query.ToList();
}
The code above results in the following SQL:
WHERE (age = 22 AND name = "phil") AND (age = 19 AND name = "dave") AND (age = 31 AND name = "nick")
What do I need to change in the expression to cause the generated SQL to use 'OR' instead of 'AND' in the indicated locations? I would prefer to avoid using third party libraries where possible.
EDIT:
As suggested by @KingKing, a union
does return the required results:
private _dbSet<user> Users { get; set; }
public List<user> CustomFilter(List<filterParm> parms)
{
IQueryable<TEntity> query = _dbSet;
if (parms.Count > 0)
{
query = query.Where(u => u.Age == parms[0].Age && u.Name == parms[0].Name);
for (int i = 1; i < parms.Count; i++)
{
var parm = parms[i];
query = query.Union(DbSet.Where(u => u.Age == parm.Age && u.Name == parm.Name));
}
}
return query.ToList();
}
I would still like to know if it is possible to generate the statement using the 'Or' operator as described.
I think using Union
will help:
public List<user> CustomFilter(List<filterParm> parms) {
IQueryable<TEntity> query = _dbSet;
if (parms.Count > 0 ){
IQueryable<TEntity> init = _dbSet;
var firstParm = parms[0];
query = query.Where(u => u.Age == firstParm.Age && u.Name == firstParm.Name);
for(int i = 1; i < parms.Count; i++)
{
var nextParm = parms[i];
init = init.Where(u => u.Age == nextParm.Age && u.Name == nextParm.Name);
query = query.Union(init);
}
}
return query.ToList();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With