4

I want to load a list of tuples from database. However, when tried like below. I am getting an error "Only parameterless constructors and initializers are supported in LINQ to Entities".

List<Tuple<string, DateTime?>> schdule = new List<Tuple<string, DateTime?>>();
schdule = Entities.ScheduleDates.Where(x => x.Code == cCode).Select(x => new Tuple<string, DateTime?>(x.Key, x.Time)).ToList<Tuple<string, DateTime?>>();

However, by using anonymous types I don't get any error.

var tempSchedule = Entities.ScheduleDates.Where(x => x.Code == cCode).Select(x => new { x.Key, x.Time }).ToList();

Why I am facing the above error.

Darey
  • 497
  • 4
  • 24
  • 1
    because _Only parameterless constructors and initializers are supported in LINQ to Entities_ – Selman Genç Aug 04 '14 at 09:42
  • Duplicated with http://stackoverflow.com/a/13875074, maybe [second answer](http://stackoverflow.com/a/13875074/19046) "If you still want to use your constructor for initialization and not properties (...), enumerate the query by calling ToList() or ToArray(), and then use Select(…)." is more useful to you. – DaniCE Aug 04 '14 at 09:45

1 Answers1

1

Because LINQ to Entities queries are translated to SQL queries, so each operation you do must have an equivalent in SQL.

Constructors which are nothing more than methods can't be translated.

But instantiating an anonymous type can, it will simply be translated as:

SELECT someAlias.Key, someAlias.Time ...
Pragmateek
  • 13,174
  • 9
  • 74
  • 108