我需要这样的东西: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)
我需要这样的东西: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)
不是直接的。请记住,_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));
尽管。
我通常使用下一个表单来构建带有 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.Users.Where(u => (u.Id == 1 || u.Id == 2));