|
| 1 | +using ContainRs.Api.Contracts; |
| 2 | +using ContainRs.Domain.Models; |
| 3 | +using Microsoft.EntityFrameworkCore; |
| 4 | +using System.Linq.Expressions; |
| 5 | + |
| 6 | +namespace ContainRs.Api.Data.Repositories; |
| 7 | + |
| 8 | +public class ClienteRepository(AppDbContext dbContext) : IRepository<Cliente> |
| 9 | +{ |
| 10 | + public async Task<Cliente> AddAsync(Cliente cliente, CancellationToken cancellationToken = default) |
| 11 | + { |
| 12 | + await dbContext.Clientes.AddAsync(cliente, cancellationToken); |
| 13 | + await dbContext.SaveChangesAsync(cancellationToken); |
| 14 | + return cliente; |
| 15 | + } |
| 16 | + |
| 17 | + public async Task<IEnumerable<Cliente>> GetWhereAsync(Expression<Func<Cliente, bool>>? filtro = null, CancellationToken cancellationToken = default) |
| 18 | + { |
| 19 | + IQueryable<Cliente> queryClientes = dbContext.Clientes; |
| 20 | + if (filtro != null) |
| 21 | + { |
| 22 | + queryClientes = queryClientes.Where(filtro); |
| 23 | + } |
| 24 | + return await queryClientes |
| 25 | + .AsNoTracking() |
| 26 | + .ToListAsync(cancellationToken); |
| 27 | + } |
| 28 | + |
| 29 | + public async Task<Cliente?> GetFirstAsync<TProperty>(Expression<Func<Cliente, bool>> filtro, Expression<Func<Cliente, TProperty>> orderBy, CancellationToken cancellationToken = default) |
| 30 | + { |
| 31 | + return await dbContext.Clientes |
| 32 | + .Include(c => c.Enderecos) |
| 33 | + .AsNoTracking() |
| 34 | + .OrderBy(orderBy) |
| 35 | + .FirstOrDefaultAsync(filtro, cancellationToken); |
| 36 | + } |
| 37 | + |
| 38 | + public async Task RemoveAsync(Cliente cliente, CancellationToken cancellationToken = default) |
| 39 | + { |
| 40 | + dbContext.Clientes.Remove(cliente); |
| 41 | + await dbContext.SaveChangesAsync(cancellationToken); |
| 42 | + } |
| 43 | + |
| 44 | + public async Task<Cliente> UpdateAsync(Cliente cliente, CancellationToken cancellationToken = default) |
| 45 | + { |
| 46 | + // verificando endereços a serem removidos |
| 47 | + dbContext.Set<Endereco>() |
| 48 | + .Where(e => e.ClienteId == cliente.Id && !cliente.Enderecos.Contains(e)) |
| 49 | + .ToList() |
| 50 | + .ForEach(e => dbContext.Set<Endereco>().Remove(e)); |
| 51 | + |
| 52 | + dbContext.Clientes.Update(cliente); |
| 53 | + await dbContext.SaveChangesAsync(cancellationToken); |
| 54 | + return cliente; |
| 55 | + } |
| 56 | +} |
0 commit comments