11

I need to extract a list of couple 'ID'/'Name' from a large table in C# .NET with Entity Framework.

I try this request :

List<Tuple<int, string>> list = (from res in db.Resource 
                                 select new Tuple<int, string>(res.Resource_ID, res.Name)).ToList();

But unfortunately I've got this error :

Only parameterless constructors and initializers are supported in LINQ to Entities.

I don't undestand how can I extract this list of tuple with this framework and I feel a bit lost with this error. Can you help me to understand and resolve my problem ?

Best regards,

Alex

Masoud
  • 8,044
  • 9
  • 56
  • 115
Alex
  • 2,769
  • 8
  • 32
  • 54

2 Answers2

17

You can do it with a middle-step by selecting an anonymous type:

db.Resource.Select(x => new { x.Resource_ID, x.Name }).AsEnumerable().Select(x => Tuple.Create(x.Resource_ID, x.Name)).ToList();

Creating a tuple is not a supported operation in Linq To Entities, so you have to select an anonymous type, which would be an equivalent to:

SELECT [Resource].[Resource_ID], [Resource].[Name]

then move to LINQ to Objects by AsEnumerable and get your tuple.

Tim Rogers
  • 20,618
  • 6
  • 50
  • 67
Patryk Ćwiek
  • 13,700
  • 3
  • 53
  • 75
  • +1 for using the anonymous type to reduce the amount of data being transferred from the DB. – juharr May 14 '13 at 12:34
2

You can create a list from db.Resource and use LINQ to Collections to erase this limitation:

var list = db.Resource.ToList().Select(res => Tuple.Create(res.Resource_ID, res.Name));

The Tuple class does have some constructors (up to 8 items), but the Create() helper method makes the creation more straightforward.

Omar
  • 15,543
  • 9
  • 43
  • 64