如何在Where子句中使用'Or'?

时间:2012-11-24 18:13:46

标签: entity-framework

我需要这样的事情:Select name from users where id = 1 or id = 2。 我知道我可以这样做:

_db.Users
.Where(u => u.Id == 1 || u.Id == 2);

但除此之外还有其他选择吗? 有这样的事情:

_db.User
.Where(u => u.Id == 1)
.Or
.Where(u => u.Id == 2)

3 个答案:

答案 0 :(得分:2)

不直接。请记住,_db.Users.Where(u => u.Id == 1)是id为1的用户。您无法从中获取ID为2的用户,因为它不存在。

您可以使用其他方法,例如

var user1 = _db.Users.Where(u => u.Id == 1);
var user2 = _db.Users.Where(u => u.Id == 2);
var users = user1.Union(user2);

var userids = new int[] { 1, 2 };
var users = _db.Users.Where(u => userids.Contains(u.Id));

虽然。

答案 1 :(得分:2)

我通常使用下一个表单来构建带有OR和AND的动态linq。

public class Linq
{
 public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expression1,
                                                        Expression<Func<T, bool>> expression2)
{
        if (expression1 == null) throw new ArgumentNullException("expression1", "Consider setting expression1 to Linq.True<T>() or Linq.False<T>()");
        var invokedExpr = Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
              (Expression.OrElse(expression1.Body, invokedExpr), expression1.Parameters);
}


public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expression1,
                                                         Expression<Func<T, bool>> expression2)
    {
        if (expression1 == null) throw new ArgumentNullException("expression1", "Consider setting expression1 to Linq.True<T>() or Linq.False<T>()");
        var invokedExpr = Expression.Invoke(expression2, expression1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
              (Expression.AndAlso(expression1.Body, invokedExpr), expression1.Parameters);
    }

public static Expression<Func<T, bool>> True<T>() { return f => true; }
public static Expression<Func<T, bool>> False<T>() { return f => false; }
}

然后在您的代码中使用它:

Expression<Func<User, bool>> searchExpression = Linq.False<User>();

searchExpression = Linq.Or<User>(searchExpression, b => b.Id==1);
searchExpression = Linq.Or<User>(searchExpression, b => b.Id==2);

然后将此searchExpression用作

_db.Users.Where(searchExpression);

使用此表单可以非常轻松地构建动态查询,例如:

Expression<Func<User, bool>> searchExpression = Linq.False<User>();
searchExpression = Linq.Or<User>(searchExpression, b => b.Id==1);
if (!String.IsNullOrEmpty(name))
    searchExpression = Linq.Or<User>(searchExpression, b => b.Name.StartsWith(name));
//combine with OR / AND as much as you need

它只会向DB生成一个查询。

答案 2 :(得分:0)

你只想:

_db.Users.Where(u => (u.Id == 1 || u.Id == 2));