实体框架动态Lambda执行搜索

问题描述:

我在Entity Framwork 5 (C#)中具有以下实体:

OrderLine - Id, OrderId, ProductName, Price, Deleted

Order - Id, CustomerId, OrderNo, Date

Customer - Id, CustomerName

在订单搜索屏幕上,用户可以输入以下搜索值:

On the order search screen the user can enter the following search values:

ProductName, OrderNo, CustomerName

例如,他们可以输入:

Product Search Field: 'Car van bike'

Order Search Field: '100 101 102'

Customer Search Field: 'Joe Jack James'

这应该对每个输入的单词进行OR搜索(最好使用linq到实体),此示例将在sql中输出以下内容.

This should do a OR search (ideally using linq to entities) for each entered word, this example would output the following where sql.

(ProductName like 'Car' Or ProductName like 'van' Or ProductName like 'bike') AND

(OrderNo like '100' Or OrderNo like '101' Or OrderNo like '102') AND

(CustomerName like 'Joe' Or CustomerName like 'Jack' Or CustomerName like 'James')

我想对实体使用linq来做到这一点,我猜测这将是某种动态的lambda构建器,因为我们不知道用户可能在每个字段中输入多少个单词.

I want to do this using linq to entities, i am guessing this would need to be some sort of dynamic lambda builder as we don't know how many words the user might enter into each field.

我该怎么做,我浏览了一下却看不到任何简单的东西.

How would i go about doing this, i have had a quick browse but cant see anything simple.

您可以使用表达式树.您需要做的就是拆分值并构建表达式.然后,您可以将其转换为这样的lambda表达式,

You can build a lambda expression using Expression Trees . What you need to do is split the value and build the expression . Then you can convert in in to a lambda expression like this,

var lambda = Expression.Lambda<Func<object>>(expression);  

此处是一个示例