Handler.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. using Application.Abstractions.Data;
  2. using Application.Abstractions.Messaging;
  3. using Domain.Entities.Forum.ValueObject;
  4. using Microsoft.EntityFrameworkCore;
  5. namespace Application.Features.Forum.CommentReaction.Delete;
  6. public sealed class Handler(IAppDbContext db) : ICommandHandler<Command>
  7. {
  8. public async Task Handle(Command request, CancellationToken ct)
  9. {
  10. if (request.IDs is null || request.IDs.Length == 0)
  11. {
  12. return;
  13. }
  14. var reactions = await db.CommentReaction.Where(c => request.IDs.Contains(c.ID)).ToListAsync(ct);
  15. var commentIDs = reactions.Select(c => c.CommentID).Distinct().ToList();
  16. var comments = await db.Comment.Where(c => commentIDs.Contains(c.ID)).ToListAsync(ct);
  17. foreach (var comment in comments)
  18. {
  19. var likes = reactions.Count(c => c.CommentID == comment.ID && c.Reaction == Reaction.Like);
  20. var dislikes = reactions.Count(c => c.CommentID == comment.ID && c.Reaction == Reaction.Dislike);
  21. comment.Likes -= likes;
  22. comment.Dislikes -= dislikes;
  23. comment.UpdatedAt = DateTime.UtcNow;
  24. }
  25. db.CommentReaction.RemoveRange(reactions);
  26. await db.SaveChangesAsync(ct);
  27. }
  28. }