简体   繁体   中英

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. 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:

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 does not recognize the method Contains...."

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.

Since your question is tagged as C# 4 use a List<string> instead ( StringCollection is ancient) and your query should work. 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... :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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