wilsonsantosphx

Mapper

Aug 14th, 2025
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.46 KB | None | 0 0
  1. // =======================
  2. // Camada de Aplicação (DTO)
  3. // Obs.: Declaramos os operadores AQUI para evitar acoplar o Domínio a DTOs.
  4. // =======================
  5. public sealed class PedidoDto
  6. {
  7.     public string? Id { get; init; }
  8.     public string? Cliente { get; init; }
  9.     public DateTime? Data { get; init; }
  10.     public decimal? Total { get; init; }
  11.  
  12.     // Conversão EXPLÍCITA: DTO -> Domain (pode falhar por validação; exige cast)
  13.     public static explicit operator Pedido?(PedidoDto? dto)
  14.     {
  15.         if (dto is null) return null;
  16.         // Validações mínimas antes de ir ao domínio
  17.         if (string.IsNullOrWhiteSpace(dto.Id)) throw new ArgumentException("Id obrigatório no DTO");
  18.         if (string.IsNullOrWhiteSpace(dto.Cliente)) throw new ArgumentException("Cliente obrigatório no DTO");
  19.         if (dto.Data is null) throw new ArgumentException("Data obrigatória no DTO");
  20.         if (dto.Total is null) throw new ArgumentException("Total obrigatório no DTO");
  21.  
  22.         return Pedido.Criar(dto.Id!, dto.Cliente!, dto.Data.Value, dto.Total.Value);
  23.     }
  24.  
  25.     // Conversão IMPLÍCITA: Domain -> DTO (não deve falhar; sem perda de info)
  26.     public static implicit operator PedidoDto?(Pedido? model)
  27.     {
  28.         if (model is null) return null;
  29.         return new PedidoDto
  30.         {
  31.             Id = model.Id,
  32.             Cliente = model.Cliente,
  33.             Data = model.Data,
  34.             Total = model.Total
  35.         };
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment