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 CategoryRepository : ICategoryRepository
{
// FIELDS FOR CTOR
private readonly ApplicationDbContext _context;
// CTOR
public CategoryRepository(ApplicationDbContext context)
{
_context = context;
}
// CREATE
public async Task<Category?> AddAsync(Category category)
{
await _context.Categories.AddAsync(category);
await _context.SaveChangesAsync();
return category;
}
// READ ALL
public async Task<IEnumerable<Category>> GetAllAsync()
{
return await _context.Categories.ToListAsync();
}
// READ BY ID
public async Task<Category?> GetByIdAsync(int id)
{
return await _context.Categories.FindAsync(id);
}
// READ BY NAME
public async Task<Category?> GetByNameAsync(string name)
{
return await _context.Categories.FirstOrDefaultAsync(n => n.Name == name);
}
// UPDATE
public async Task<bool> UpdateAsync(Category category)
{
_context.Entry(category).State = EntityState.Modified;
var results = await _context.SaveChangesAsync();
return results > 0;
}
// DELETE
public async Task<bool> DeleteAsync(Category category)
{
_context.Categories.Remove(category);
var result = await _context.SaveChangesAsync();
return result > 0;
}
}
}