[英]Using StringCollection specified in Application Settings in a LINQ-to-Entities Query
In my application, I have Property Setting which is of type String.Collections.Specialized.StringCollection. 在我的应用程序中,我有属性设置,其类型为String.Collections.Specialized.StringCollection。 It contains a list of customer codes such as MSFT, SOF, IBM etc. I'm trying to use this in a Linq-to-Entities query in the where clause:
它包含一系列客户代码,例如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)));
This fails as Contains is not recognized by Linq-to-Entities with a message similar to: 这失败,因为Linq-to-Entities无法识别包含类似于以下消息的包含:
"LINQ-to-Entities does not recognize the method Contains...." “LINQ-to-Entities无法识别方法包含......”
How do I revise the code above to avoid this error? 如何修改上面的代码以避免此错误?
A shorter path is 较短的路径是
myProperties.Settings.Default.CustomersToExclude.Cast<string>().Contains(blah);
That's a handy trick for any situation where a collection isn't inherently LINQ-aware. 对于任何集合本身不支持LINQ的情况,这是一个方便的技巧。
Since your question is tagged as C# 4 use a List<string>
instead ( StringCollection
is ancient) and your query should work. 由于您的问题被标记为C#4,请使用
List<string>
( StringCollection
很古老)并且您的查询应该有效。 Also you should resolve your list reference outside your query: 您还应该在查询之外解析列表引用:
List<string> customersToExclude = ..
var ShippedOrders = dbcontext.Orders
.Where(s=>(s.Status.Description.Equals("Shipped")
&& !customersToExclude.Contains(s.CustomerCode)));
Edit: 编辑:
Just copy your customers to an array and use that: 只需将您的客户复制到一个数组并使用它:
var customerstoExclude = new string[Properties.Settings.Default.CustomersToExclude.Count];
myProperties.Settings.Default.CustomersToExclude.CopyTo(customerstoExclude, 0);
This is answered in a related question . 这在相关问题中得到了回答 。 EF4 apparently supports Contains directly, though, so that'd be my prefered solution... :)
EF4显然支持直接包含,所以这是我的首选解决方案...... :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.