给出以下形式的过滤器参数列表:
public class filterParm
{
public int age { get; set; }
public string name { get; set; }
}
其中:
var parms = new List<filterParm>
{
new filterParm {age = 22, "phil"},
new filterParm {age = 19, "dave"},
new filterParm {age = 31, "nick"}
};
如何编写一个表达式,该表达式将导致以下SQL where子句(请注意 OR 运算符的粗体:
WHERE(年龄= 22岁,姓名=“phil”)
OR (年龄= 19 AND name =“dave”)
OR (年龄= 31 AND name =“nick”)
我当前的实现会导致 AND 运算符分隔的每个语句:
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();
}
上面的代码导致以下SQL:
WHERE(年龄= 22 AND name =“phil”) AND (年龄= 19岁 AND name =“dave”) AND (年龄= 31 AND name =“nick”)
我需要在表达式中更改以使生成的SQL在指定位置使用“OR”而不是“AND”?我希望尽可能避免使用第三方库。
编辑:
正如@KingKing所建议的那样,union
会返回所需的结果:
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();
}
我仍然想知道是否可以使用'Or'运算符生成语句。
答案 0 :(得分:1)
我认为使用Union
会有所帮助:
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();
}