EF 相关问题:Linq的where条件如何在循环中写OR

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/iceagezh/article/details/78126148

问题描述:

EF中我要:查询表A,实现条件:where 或..或..或..

传统的方法是:

var query = from a in db.A 
            where a.a==1 || a.a==2 || a.a==3
            select a


但是当如果where条件中“或”关系的个数不确定,且是动态的,怎么办?

【解决方法】

步骤一:

添加静态类,扩展where条件

static class PredicateBuilder
    {
        public static Expression<Func<T, bool>> True<T>() { return f => true; }
        public static Expression<Func<T, bool>> False<T>() { return f => false; }
        //false
        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
                                                            Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.Or(expr1.Body, invokedExpr), expr1.Parameters);
        }
        //true
        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
                                                             Expression<Func<T, bool>> expr2)
        {
            var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
            return Expression.Lambda<Func<T, bool>>
                  (Expression.And(expr1.Body, invokedExpr), expr1.Parameters);
        }
}

步骤二:

调用该方法:

   var where = PredicateBuilder.False<A>();//A为Model

  foreach (string t in terms)
  {
      where = where.Or(n => n.whatever== t);//实现或关系连接
  }
  query = query.Where(where.Compile()); //将条件附加到原查询结果中

步骤三:

当完成上述两个步骤后,编译会发现类型转换的错误。只需要在最初的查询时定义下类型(添加.AsEnumerable())即可:

var query = from a in db.A.AsEnumerable() select a

猜你喜欢

转载自blog.csdn.net/iceagezh/article/details/78126148
EF