首页 文章

实体框架的通用过滤机制的条件逻辑

提问于
浏览
0

我正在寻找为我的应用程序服务实现通用的过滤和排序机制 .

做了一些研究之后,似乎LINQKit对于使用谓词构建器来说是理想的 . 我还发现一些文章在实现方面有一些很好的细节:

然而,我没见过的一件事是WHERE子句的条件逻辑 . 我看到的每个例子似乎只是和那里的条件 .

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

WHERE((Field1 = 1 OR Field1 = 2)AND Field2 = 3)OR Field4 ='A'

有没有人看到过将条件逻辑添加到过滤器的通用实现中的实现?

1 回答

  • 1

    表达树可能是你的答案 . 这里也是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();
    

相关问题