Handler.cs 2.0 KB

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