2024-06-28 15:15:15 +02:00

65 lines
1.8 KiB
C#

using AutoMapper;
using Microsoft.EntityFrameworkCore;
using Project.Domain.Entities;
using Project.Infrastructure.Interfaces;
namespace Project.Infrastructure.Repositories
{
public class ProductRepository : IProductRepository
{
// FIELDS FOR CTOR
private readonly ApplicationDbContext _context;
private readonly IMapper _mapper;
// CTOR
public ProductRepository(ApplicationDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
// CREATE
public async Task<Product?> AddAsync(Product product)
{
await _context.Products.AddAsync(product);
await _context.SaveChangesAsync();
return product;
}
// READ ALL
[Authorize]
public async Task<IEnumerable<Product>> GetAllAsync()
{
return await _context.Products.Include(p => p.Category).ToListAsync();
}
// READ BY ID
public async Task<Product?> GetByIdAsync(int id)
{
return await _context.Products.FindAsync(id);
}
// READ BY NAME
public async Task<Product?> GetByNameAsync(string name)
{
return await _context.Products.FirstOrDefaultAsync(n => n.Name == name);
}
// UPDATE
public async Task<bool> UpdateAsync(Product product)
{
_context.Entry(product).State = EntityState.Modified;
var results = await _context.SaveChangesAsync();
return results > 0;
}
// DELETE
public async Task<bool> DeleteAsync(Product product)
{
_context.Products.Remove(product);
var result = await _context.SaveChangesAsync();
return result > 0;
}
}
}