Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Projecting into KeyValuePair via EF / Linq

I'm trying to load a list of KeyValuePairs from an EF / Linq query like this:

return (from o in context.myTable 
select new KeyValuePair<int, string>(o.columnA, o.columnB)).ToList();

My problem is that this results in the error

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

Is there an easy way around this? I know I could create a custom class for this instead of using KeyValuePair but that does seem like re-inventing the wheel.

like image 454
GrandMasterFlush Avatar asked Jun 25 '13 15:06

GrandMasterFlush


2 Answers

Select only columnA and columnB from your table, and move further processing in memory:

return context.myTable
              .Select(o => new { o.columnA, o.columnB }) // only two fields
              .AsEnumerable() // to clients memory
              .Select(o => new KeyValuePair<int, string>(o.columnA, o.columnB))
              .ToList();

Consider also to create dictionary which contains KeyValuePairs:

return context.myTable.ToDictionary(o => o.columnA, o => o.columnB).ToList();
like image 50
Sergey Berezovskiy Avatar answered Oct 29 '22 20:10

Sergey Berezovskiy


Since LINQ to Entities does not support KeyValuePair, you should turns to LINQ to Object by using AsEnumerable first:

return context.myTable
              .AsEnumerable()
              .Select(new KeyValuePair<int, string>(o.columnA, o.columnB))
              .ToList();
like image 10
cuongle Avatar answered Oct 29 '22 20:10

cuongle