views:

1340

answers:

1

So, I'm trying to return a collection of People whose ID is contained within a locally created collection of ids ( IQueryable)

When I specify "locally created collection", I mean that the Ids collection hasnt come from a LinqToSql query and has been programatically created (based upon user input). My query looks like this:

var qry = from p in DBContext.People
                  where Ids.Contains(p.ID)
                  select p.ID;

This causes the following exception...

"queries with local connections are not supported"

How can I find all the People with an id that is contained within my locally created Ids collection?

Is it possible using LinqToSql?

+9  A: 

If Ids is a List, array or similar, L2S will translate into a contains.

If Ids is a IQueryable, just turn it into a list before using it in the query. E.g.:

List listOfIDs = IDs.ToList();
var query =
from st in dc.SomeTable
where listOfIDs.Contains(st.ID) select .....

KristoferA - Huagati.com
I think the solution to your problem is more nuanced than this answer. I'm using the same construction (a Contains method on an IQueryable in a WHERE clause) successfully, and LINQ to SQL translates it into a WHERE EXISTS clause in the SQL query. It seems to work in some situations and not others, so you should post how you get your Ids IQueryable, as that may shed some light on the issue.
John Bledsoe
@jmbledsoe if my answer wasn't clear enough: L2S expects a local IEnumerable (not a deferred IQueryable) passed to Enumerable.Contains. If you pass it a local query, that can not be translated to a SQL query. If you pass it a list/array/etc then it can be translated into a SQL "where ... in (x, y, ..., n)" clause.
KristoferA - Huagati.com
I think I see what you're saying:- Passing a List/Array/etc. is OK b/c it will generate a WHERE ... IN clause.- Passing a deferred IQueryable is OK b/c it will integrate with the current deferred query.- Passing a local IEnumerable is NOT OK, but you can just .ToList() it and it will be fine.
John Bledsoe
Yes, that pretty much sums it up.
KristoferA - Huagati.com