public async Task <IActionResult> GetWork(string slug) { var works = await context.Works.Include(x => x.Author).Include(x => x.WorkGenres).Include(x => x.Comments).ToListAsync(); var work = works.Find(work => work.Slug == slug); List <CommentDTO> commentDTOs = new List <CommentDTO>(); foreach (var comment in work.Comments) { commentDTOs.Add(new CommentDTO() { AuthorName = comment.Author.UserName, CreationDate = comment.CreationDate, Value = comment.Value, WorkSlug = work.Slug }); } WorkDTO workDTO = new WorkDTO() { AuthorName = work.Author.UserName, Genres = WorkGenre.GenresToList(work.WorkGenres), Name = work.Name, Body = work.Body, Comments = commentDTOs, Slug = work.Slug }; return(Ok(workDTO)); }
public async Task <IActionResult> GetAll(string searchString) { context.Comments.Include(x => x.Author); var works = await context.Works.Include(x => x.WorkGenres).Include(x => x.Comments).ThenInclude(x => x.Author).ToListAsync(); List <WorkDTO> worksDto = new List <WorkDTO>(); List <CommentDTO> commentDTOs = new List <CommentDTO>(); if (!string.IsNullOrEmpty(searchString)) { works = works.Where(x => x.Name.Contains(searchString) || x.Author.UserName.Contains(searchString)).ToList(); } foreach (var item in works) { commentDTOs = new List <CommentDTO>(); foreach (var comment in item.Comments) { commentDTOs.Add(new CommentDTO() { AuthorName = comment.Author.UserName, CreationDate = comment.CreationDate, Value = comment.Value, WorkSlug = item.Slug }); } worksDto.Add(new WorkDTO() { AuthorName = item.Author.UserName, Body = item.Body, Genres = WorkGenre.GenresToList(item.WorkGenres), Name = item.Name, Slug = item.Slug, Comments = commentDTOs }); } return(Ok(worksDto)); }