title: If repository shouldn't return DTO, how can I return entities with number of children entities?
body: <p>I have read repository shouldn't return DTO but entity. So how can I return list of entities with number of children entities?</p>
  
  <p>That is mine entity in database:</p>
  
  <pre><code>public class Note
  {
      [Key] 
      public int NoteId { get; set; }
  
      [Required]
      public string Content { get; set; }
  
      public virtual ICollection&lt;Comment&gt; Comments { get; set; }
  }
  </code></pre>
  
  <p>Now I have in repository:</p>
  
  <pre><code>public IEnumerable&lt;Note&gt; GetNotes()
  {
      return context.Notes.OrderBy(x =&gt; x.Title).ToList();
  }
  </code></pre>
  
  <p>and in service:</p>
  
  <pre><code>public class NoteWithCommentsCountDTO
  {
      public Note Note { get; set; }
      public int NoteCommentsCount { get; set; }
  }
  
  public IEnumerable&lt;NoteWithCommentsCountDTO&gt; GetNotesWithNoSpamCommentsCount()
  {
      IEnumerable&lt;NoteWithCommentsCountDTO&gt; notesDTO = _notesRepository.GetNotes()
          .Select(x =&gt;
          new NoteWithCommentsCountDTO
          {
              Note = x,
              NoteCommentsCount = x.Comments.Where(y =&gt; y.IsSpam == false).Count()
          });
  
      return notesDTO;
  }
  </code></pre>
  
  <p>Unfortunatelly Entity Framework generates as many SQL queries as number of notes.</p>
  
  <p>I can eliminate that problem if I use DTO in repository:</p>
  
  <pre><code>public IEnumerable&lt;NoteWithCommentsCountDTO&gt; GetNotesWithNoSpamCommentsCount()
  {
      IQueryable&lt;NoteWithCommentsCountDTO&gt; notesDTO = context.Notes
          .Include(x =&gt; x.Comments)
          .OrderBy(x =&gt; x.Title)
          .Select(x =&gt;
          new NoteWithCommentsCountDTO
          {
              Note = x,
              NoteCommentsCount = x.Comments.Where(y =&gt; y.IsSpam == false).Count() 
          }).ToList();
  
      return notesDTO;
  }
  </code></pre>
  
  <p>Now Entity Framework generates one SQL query but I return DTO from repository, not entity - what is the solution?</p>