No LINQ query with GroupBy method

 public class ReportDto { public DateTime Date { get; set; } public WordDto[] Words { get; set; } } ReportDto[] qwe = this.context.TestResults .Where(r => r.Word.Vocabulary.VocabularyID == id) .GroupBy(r => r.Date) .Select(r => new ReportDto { Date = r.Key, Words = r.Select(re => new WordDto { ID = re.WordID.ToString(), Original = re.Word.Original, Translate = re.Word.Translation, Result = re.Result }).ToArray() }).ToArray(); 

Mistake:

Additional information: LINQ to Entities doesn’t recognize the Core.Dto.WordDto [] ToArrayWordDto method.

  • 2
    IMHO, .AsEnumerable() after .GroupBy(r => r.Date) . - PetSerAl pm
  • @PetSerAl Thanks, can you tell me what this method gives? - Jitsu
  • one
    @Jitsu AsEnumerable turns the following select into an Enumerable.Select call, which, when running ToArray below, begins to iterate over the objects from the GroupBy result one by one, turning them into ReportDto. Without an AsEnumerable call, your Select remains a Queryable.Select, which does not iterate over objects, but simply adds a Select call to the query tree. Which LINQ to Entities is trying to reflect in SQL and execute on the SQL Server side. And it cannot (for various reasons, but in this case - because it does not overpower your request. - PashaPash
  • one
    @Jitsu TLDR all before AsEnumerable runs on the base, after - in memory. - PashaPash
  • Well, complete your answer,% somebody%! - VladD

3 answers 3

 public class ReportDto { public DateTime Date { get; set; } public WordDto[] Words { get; set; } } ReportDto[] qwe = this.context.TestResults .Where(r => r.Word.Vocabulary.VocabularyID == id) .GroupBy(r => r.Date) .AsEnumerable() .Select(r => new ReportDto { Date = r.Key, Words = r.Select(re => new WordDto { ID = re.WordID.ToString(), Original = re.Word.Original, Translate = re.Word.Translation, Result = re.Result }).ToArray() }).ToArray(); 

    You have a problem in the first toarray (). IQeryable works with expression trees and just can't chew it.

        ReportDto[] qwe = (from elem in this.context.TestResults where elem.Word.Vocabulary.VacabularyID == id group elem by elem.Date into groupElem select new ReportDto { Date = groupElem.Key, Words = (from w_elem in groupElem.AsEnumerable() select new WordDto { ID = w_elem.WordID.ToString(), Original = w_elem.Word.Original, Translate = w_elem.Word.Translation, Result = w_elem.Result }).ToArray() }).ToArray(); 

      However, I suspect what is needed: Words = (from w_elem in groupElem.Value.AsEnumerable()