实体框架的通用筛选机制的条件逻辑



我正在考虑为我的应用程序服务实现一种通用的过滤和排序机制。

在做了一些研究之后,LINQKit似乎是使用谓词生成器实现这一点的理想选择。我还发现了一些文章,其中详细介绍了实现:

  • http://www.codeproject.com/Articles/493917/Dynamic-Querying-with-LINQ-to-Entities-and-Express
  • http://www.codeproject.com/Tips/582450/Build-Where-Clause-Dynamically-in-Linq

然而,有一件事我没见过有人做,那就是WHERE子句的条件逻辑。我看到的每一个例子似乎都只涉及到AND的条件。

我正在寻找一些可以构建更复杂表达式的东西,例如:

其中((Field1=1或Field1=2)AND Field2=3)或Field4='A'

有人见过在过滤器的通用实现中添加条件逻辑的实现吗?

表达式树可能是您的答案。这里还有OR条件和更多可能的条件。这里是我的例子:

        IQueryable<ENTITY> query = context.ENTITY;
        Expression whereExpression = null;
        ParameterExpression pe = Expression.Parameter(typeof(ENTITY), "name");
        Expression left1 = MemberExpression.Property(pe, "Field1");
        Expression right1 = Expression.Constant(1, typeof(int));
        whereExpression = Expression.And(whereExpression, Expression.Equal(left1, right1));
        Expression left2 = MemberExpression.Property(pe, "Field1");
        Expression right2 = Expression.Constant(2, typeof(int));
        whereExpression = Expression.Or(whereExpression, Expression.Equal(left2, right2));
        Expression left3 = MemberExpression.Property(pe, "Field2");
        Expression right3 = Expression.Constant(3, typeof(int));
        whereExpression = Expression.And(whereExpression, Expression.Equal(left3, right3));
        Expression left4 = MemberExpression.Property(pe, "Field4");
        Expression right4 = Expression.Constant("A", typeof(string));
        whereExpression = Expression.Or(whereExpression, Expression.Equal(left4, right4));
        Expression<Func<ENTITY, bool>> whereCondition = Expression.Lambda<Func<ENTITY, bool>>(whereExpression, new ParameterExpression[] { pe });
        query = query.Where(whereCondition);
        return query.ToList();

最新更新