5

给定以下形式的过滤器参数列表:

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 (age = 22 AND name = "phil")
OR (age = 19 AND name = "dave") OR (age = 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 (age = 22 AND name = "phil") AND (age = 19 AND name = "dave") AND (age = 31 AND name = "nick")

我需要在表达式中进行哪些更改以使生成的 SQL 在指定位置使用“OR”而不是“AND”?我宁愿尽可能避免使用第三方库。

编辑:正如@KingKing 所建议的, aunion确实返回了所需的结果:

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

我仍然想知道是否可以使用所描述的“或”运算符生成语句。

4

1 回答 1

2

我认为使用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();
}
于 2013-09-17T09:36:34.403 回答