tags:

views:

16

answers:

2

I'm struggling to get what I thought would be a simple LINQ-to-SQL query to work. I can construct the query ok and can verify that the SQL it generates is correct but when executing get the dreaded "System.NotSupportedException: Queries with local collections are not supported" exception.

I've simplified my query but in short the query below works:

var query = from asset in context where new[] { 1, 2, 3 }.Contains(asset.code) select asset

this query also works:

var query = from asset in context where new List<int>() { 1, 2, 3 }.Contains(asset.code) select asset

But the query below will fail when an attempt is made to get the result set:

List<int> myList = new List<int>(){1, 2, 3};
var query = from asset in context where myList.Contains(asset.code) select asset

Anyone solved this sort of issue?

A: 

This works fine for me in LINQPad:

List<int> myList = new List<int>(){1, 2, 3}; /* Fixed your compiler error here */
var query = from asset in assets where myList.Contains(asset.code) select asset; 

As such, I assume you aren't actually using a List for myList, but rather a generic IEnumerable or something similar?

Please try pasting your "unsimplified" version, as your simplication corrects your error.

Graphain
I fixed the error, thanks. The issue isn't the LINQ query or even the generation of the SQL, both work correctly. The exception occurs when the query is sent to the database and for some reason the linq-to-sql logic spits the dummy when it sees a local collection within the query even though it is able to generate the SQL and parameteres.
sipwiz
How did you fix it?
Graphain
+1  A: 

What you posted should work, leading me to believe you didn't actually post the broken code.

Make sure that the MyList variable is a List<int> and not an IList<int>... if the variable type is IList<int>, you'd get that exception.

David B
Yep, that's what i thought too. If you pass in a List, it'll pass each list element as a sql parameter and use IN (@p1, @p2) etc. IList will cause the error. Here's another example - http://stackoverflow.com/questions/1084339/working-around-linqtosqls-queries-with-local-collections-are-not-supported-exce
Frank Tzanabetis