3

在我的应用程序中,我有 String.Collections.Specialized.StringCollection 类型的属性设置。它包含客户代码列表,例如 MSFT、SOF、IBM 等。我试图在 where 子句的 Linq-to-Entities 查询中使用它:

var ShippedOrders = dbcontext.Orders
 .Where(s=>(s.Status.Description.Equals("Shipped") && !Properties.Settings.Default.CustomersToExclude.Contains(s.CustomerCode)));

这会失败,因为 Linq-to-Entities 无法识别包含,并显示类似于以下内容的消息:

“LINQ-to-Entities 无法识别方法 Contains....”

如何修改上面的代码以避免此错误?

4

3 回答 3

16

更短的路径是

myProperties.Settings.Default.CustomersToExclude.Cast<string>().Contains(blah); 

对于集合本身不支持 LINQ 的任何情况,这都是一个方便的技巧。

于 2012-09-13T16:55:08.360 回答
2

由于您的问题被标记为 C# 4 使用 aList<string>代替(StringCollection是古老的)并且您的查询应该可以工作。此外,您应该在查询之外解析您的列表参考:

List<string> customersToExclude = ..
var ShippedOrders = dbcontext.Orders
                             .Where(s=>(s.Status.Description.Equals("Shipped") 
                                    && !customersToExclude.Contains(s.CustomerCode)));

编辑:

只需将您的客户复制到一个数组并使用它:

var customerstoExclude = new string[Properties.Settings.Default.CustomersToExclude.Count];
myProperties.Settings.Default.CustomersToExclude.CopyTo(customerstoExclude, 0);
于 2012-02-08T17:25:58.940 回答
1

这在相关问题中得到了回答。不过,EF4 显然直接支持 Contains,所以这将是我的首选解决方案... :)

于 2012-02-08T17:24:20.577 回答