2024-07-10 09:00:36 +02:00

62 lines
1.7 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;
// CTOR
public ProductRepository(ApplicationDbContext context)
{
_context = context;
}
// CREATE
public async Task<Product?> AddAsync(Product product)
{
await _context.Products.AddAsync(product);
await _context.SaveChangesAsync();
return product;
}
// READ ALL
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;
}
}
}