Handler.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using Application.Abstractions.Messaging;
  2. using Application.Abstractions.Data;
  3. using Application.Abstractions.Cache;
  4. using Domain.Entities.Page.Banner;
  5. using Microsoft.EntityFrameworkCore;
  6. namespace Application.Features.Admin.Banner.Position.Save;
  7. public sealed class Handler(IAppDbContext db, ICacheService cache) : ICommandHandler<Command, Response>
  8. {
  9. public async Task<Response> Handle(Command request, CancellationToken ct)
  10. {
  11. var items = request.Items ?? [];
  12. var dbRows = await db.BannerPosition.Include(x => x.BannerItems).ToListAsync(ct);
  13. var inserted = 0;
  14. var updated = 0;
  15. var deleted = 0;
  16. var incomingById = items.Where(x => x.ID.HasValue).ToDictionary(x => x.ID!.Value, x => x);
  17. foreach (var existing in dbRows)
  18. {
  19. if (!incomingById.TryGetValue(existing.ID, out var row))
  20. {
  21. if (existing.BannerItems.Count > 0)
  22. {
  23. continue;
  24. }
  25. db.BannerPosition.Remove(existing);
  26. deleted++;
  27. continue;
  28. }
  29. if (existing.Code != row.Code || existing.Subject != row.Subject || existing.IsActive != row.IsActive)
  30. {
  31. existing.Update(row.Subject, row.IsActive);
  32. if (existing.Code != row.Code)
  33. {
  34. var prop = typeof(BannerPosition).GetProperty("Code");
  35. prop?.SetValue(existing, row.Code);
  36. }
  37. updated++;
  38. }
  39. }
  40. var existingIds = dbRows.Select(x => x.ID).ToHashSet();
  41. foreach (var row in items.Where(x => !x.ID.HasValue))
  42. {
  43. if (dbRows.Any(x => x.Code == row.Code))
  44. {
  45. continue;
  46. }
  47. var entity = BannerPosition.Create(row.Code, row.Subject, row.IsActive);
  48. db.BannerPosition.Add(entity);
  49. inserted++;
  50. }
  51. if (inserted + updated + deleted > 0)
  52. {
  53. await db.SaveChangesAsync(ct);
  54. await cache.RemoveByPrefixAsync("banner:", ct);
  55. }
  56. return new Response(inserted, updated, deleted);
  57. }
  58. }