简体   繁体   English

PredicateBuilder“And”方法不起作用

[英]PredicateBuilder "And" Method not working

I have downloaded the predicate builder and am having a difficult time getting it to work with the entity framework.我已经下载了谓词构建器,但很难让它与实体框架一起工作。 Here is my code: v_OrderDetail is the entity这是我的代码: v_OrderDetail 是实体

var context = new OrdersEntities();

Expression<Func<v_OrderDetail,bool>> whereClause = w => true;                                         
var predicate = PredicateBuilder.True<v_OrderDetail>();              
predicate.And(w => w.Status == "Work");                             
var results = context.v_OrderDetail.AsExpandable().Where(predicate);

When I look at the results I get back every order.当我查看结果时,我会收到每个订单。 The And predicate doesn't seem to take. And 谓词似乎不成立。 When I look at the predicate.parameters.count it only shows 1. I'm not sure, but I would expect it to show 2 after I add the second one.当我查看 predicate.parameters.count 时,它只显示 1。我不确定,但我希望在添加第二个后它会显示 2。

Any help is greatly appreciated.任何帮助是极大的赞赏。

It's because predicate.And doesn't modify predicate , it returns a new Expression<Func<v_OrderDetail, bool>> instead.这是因为predicate.And不修改predicate ,而是返回一个新的Expression<Func<v_OrderDetail, bool>> You need to assign the result somewhere so you can use it.您需要将结果分配到某个地方,以便您可以使用它。

It will work if you do the following:如果您执行以下操作,它将起作用:

predicate = predicate.And(w => w.Status == "Work");      

The problem here is that Expression trees are immutable.这里的问题是表达式树是不可变的。 Each time you modify an expression tree you must do so by creating a brand new one with the required change.每次修改表达式树时,您都必须创建一个具有所需更改的全新表达式树。

Here's a relevant excerpt from How to modify expression trees from MSDN.这是如何修改MSDN 中的表达式树的相关摘录。

Expression trees are immutable, which means that they cannot be modified directly.表达式树是不可变的,这意味着它们不能被直接修改。 To change an expression tree, you must create a copy of an existing expression tree and when you create the copy, make the required changes.要更改表达式树,您必须创建现有表达式树的副本,并在创建副本时进行所需的更改。 You can use the ExpressionVisitor class to traverse an existing expression tree and to copy each node that it visits.您可以使用ExpressionVisitor类遍历现有的表达式树并复制它访问的每个节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM