8

I have the following Linq query:

var tmp = 
    from container in Container
    join containerType in ContainerType on container.ContainerType equals containerType
    where containerType.ContainerTypeID == 2
    select new { ContainerID = container.ContainerID, TypeID = container.ContainerTypeID};

var results = tmp.Select((row, index) => new { row.ContainerID, row.TypeID, ContainerIndex = index })

As is, this works fine. If I add the following, so I can see the results in LinqPad, I get the error described in the title of this message:

results.Dump();

This error is not a LinqPad error, it's coming from Linq, and I don't understand what it means.

Thank you.

Randy Minder
  • 47,200
  • 49
  • 204
  • 358

1 Answers1

19

Okay, I hadn't realised Container was a LINQ to SQL data source to start with. Basically it's failing to convert the second projection to SQL.

So, you want to do just that bit in .NET instead - you can force it to use Enumerable.Select with AsEnumerable:

var results = tmp.AsEnumerable()
                 .Select((row, index) => new { row.ContainerID, row.TypeID,
                                               ContainerIndex = index });
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I'm sorry, I should have mentioned that. Thanks for your help. – Randy Minder Jul 07 '10 at 12:40
  • I've encountered the same trouble, and using `.AsEnumerable()` works as well. +1. But why it works? Why from a `System.Data.Linq.Table` I can't iterate/select new object? – markzzz Jul 15 '15 at 13:20
  • @markzzz: It's a matter of where the projection happens. While it's a queryable, you're asking for whatever you're doing to be converted into SQL... whereas after you've used `AsEnumerable`, it means everything's done locally. – Jon Skeet Jul 15 '15 at 13:25
  • But why translating this into `AsEnumerable()` can do the task and without it can't? That's not clear at all... – markzzz Jul 15 '15 at 13:38
  • 1
    @markzzz: The point is you're asking for something that can't be translated into SQL, so it fails when you try to do so... whereas if you say "I'll do that projection locally" then it's fine. – Jon Skeet Jul 15 '15 at 13:38
  • But in fact I'm translating nothing into SQL; the Select is locally to my new data object structure. The only query is before the .Select :O – markzzz Jul 15 '15 at 13:43
  • @markzzz: Please read my earlier comments carefully - if you still have queries, I suggest you ask a new question with the relevant details, rather than us dragging this out into a long comment thread where I'm talking about code that you haven't presented... – Jon Skeet Jul 15 '15 at 13:47
  • Of course! Was just to learn, I don't have any troubles right now :) – markzzz Jul 15 '15 at 13:47