Question

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?

Was it helpful?

Solution

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);

OTHER TIPS

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.

This is answered in a related question. EF4 apparently supports Contains directly, though, so that'd be my prefered solution... :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top