public async Task <PagedResponse <ChatDto> > Handle(Query request, CancellationToken cancellationToken) { var chatsQuery = _db.Chats .Where(x => x.Participants.Any(p => p.UserId == request.UserId)) .OrderByDescending(x => x.Messages.Max(m => m.SentDate)) .Select(x => new ChatDto { Id = x.Id, Name = x.Name, ChatRole = x.Participants.Single(p => p.UserId == request.UserId).Role }); if (!string.IsNullOrEmpty(request.NameFilter)) { chatsQuery = chatsQuery.Where(x => x.Name.Contains(request.NameFilter)); } var pagedChats = await PaginationProcessor.GetPagedResponse((IOrderedQueryable <ChatDto>) chatsQuery, request.PaginationQuery, cancellationToken); var unreadMessages = await _db.Users.Include(x => x.UnreadMessages) .ThenInclude(x => x.Message) .Where(x => x.Id == request.UserId) .SelectMany(x => x.UnreadMessages) .ToListAsync(cancellationToken); pagedChats.Data.ForEach(x => x.UnreadMessages = unreadMessages.Where(m => m.Message.ChatId == x.Id).Count()); return(pagedChats); }
public async Task <PagedResponse <MessageDto> > Handle(Query request, CancellationToken cancellationToken) { var user = await _db.Users.Include(x => x.UnreadMessages).ThenInclude(x => x.Message).SingleOrNotFoundAsync(x => x.Id == request.UserId, cancellationToken); user.SetUnreadMessagesAsRead(request.ChatId); await _db.SaveChangesAsync(cancellationToken); var messagesQuery = _db.Messages.Where(x => x.ChatId == request.ChatId); var response = await PaginationProcessor.GetPagedResponse(messagesQuery, request.PaginationQuery, MessageDto.GetMapper(user.Id), x => x.Date, cancellationToken, false); response.Data = RemoveDeletedMessagesText(response.Data.OrderBy(x => x.Date).ToList()); return(response); }