The funkiness that is LINQ.Contains
Ok, I’m running into brick walls.
I’m trying to do this:
from p in Products
join i in new[] {1,2,3}
on p.Id equals i
select p
I get
NotSupportedException
Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains() operator.
I try again with this:
from p in Products
where ( new[] {1,2,3}).Contains (p.Id )
select p
Woot got some data back in LinqPad.
Tried this in actual code…
IList<int> ids = new List<int>(new[] {1, 2, 3});
IQueryable
from p in Products
where ids.Contains(p.Id)
select p;
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
I get
Method ‘Boolean Contains(Int32)’ has no supported translation to SQL.
But it just worked in LinqPad…
Try again:
IEnumerable<int> ids = new int[] {1, 2, 3};
IQueryable
from p in Products
where ids.Contains(p.Id)
select p;
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
Bingo.
So summary:
In LINQ, IEnumerable.Contains is only implemented for the IEnumerable interface and not the IList interface. Seems obvious now in hindsight.
Discussions