c# - If repository shouldn't return DTO, how can I return entities with number of children entities? -


i have read repository shouldn't return dto entity. how can return list of entities number of children entities?

that mine entity in database:

public class note {     [key]      public int noteid { get; set; }      [required]     public string content { get; set; }      public virtual icollection<comment> comments { get; set; } } 

now have in repository:

public ienumerable<note> getnotes() {     return context.notes.orderby(x => x.title).tolist(); } 

and in service:

public class notewithcommentscountdto {     public note note { get; set; }     public int notecommentscount { get; set; } }  public ienumerable<notewithcommentscountdto> getnoteswithnospamcommentscount() {     ienumerable<notewithcommentscountdto> notesdto = _notesrepository.getnotes()         .select(x =>         new notewithcommentscountdto         {             note = x,             notecommentscount = x.comments.where(y => y.isspam == false).count()         });      return notesdto; } 

unfortunatelly entity framework generates many sql queries number of notes.

i can eliminate problem if use dto in repository:

public ienumerable<notewithcommentscountdto> getnoteswithnospamcommentscount() {     iqueryable<notewithcommentscountdto> notesdto = context.notes         .include(x => x.comments)         .orderby(x => x.title)         .select(x =>         new notewithcommentscountdto         {             note = x,             notecommentscount = x.comments.where(y => y.isspam == false).count()          }).tolist();      return notesdto; } 

now entity framework generates 1 sql query return dto repository, not entity - solution?

you cannot entities. entities should exact equivalent of tables.

you have 2 solutions
1. either use dtos, in example
or
2. use dynamic types (it's same dtos don't have create classes). like:

public dynamic getnoteswithnospamcommentscount() {     var notesdto = _notesrepository.getnotes()         .select(x =>         new          {             note = x,             notecommentscount = x.comments.where(y => y.isspam == false).count()         });      return notesdto; } 

in opinion, option no.1 best solution, specially if you're developing n-tier application (more details on how map entities business logic check this post).


Comments