82 lines
2.9 KiB
C#
82 lines
2.9 KiB
C#
using Liber_Incantamentum.Application.Exceptions;
|
|
using Liber_Incantamentum.Domain.Entities;
|
|
using Liber_Incantamentum.Domain.Filter;
|
|
using Liber_Incantamentum.Domain.Repositories;
|
|
using Liber_Incantamentum.Infrastructure.Persistence;
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
namespace Liber_Incantamentum.Infrastructure.Repositories
|
|
{
|
|
public class MageRepository : IMageRepository
|
|
{
|
|
private readonly AppDbContext _context;
|
|
public MageRepository(AppDbContext context)
|
|
{
|
|
_context = context;
|
|
}
|
|
public async Task<bool> AddMageAsync(Mage entity)
|
|
{
|
|
await _context.Mages.AddAsync(entity);
|
|
if (!_context.ChangeTracker.HasChanges()) return false;
|
|
return await _context.SaveChangesAsync() > 0;
|
|
}
|
|
|
|
public async Task<bool> DeleteMageAsync(Guid id)
|
|
{
|
|
var mage = await GetMageByIdAsync(id);
|
|
_context.Mages.Remove(mage);
|
|
if (!_context.ChangeTracker.HasChanges()) return false;
|
|
return await _context.SaveChangesAsync() > 0;
|
|
}
|
|
|
|
public async Task<ICollection<Mage>> GetAllMagesAsync(MageFilter filterEntity)
|
|
{
|
|
var query = _context.Mages.AsQueryable();
|
|
|
|
if (filterEntity.Id != Guid.Empty)
|
|
query = query.Where(m => m.Id == filterEntity.Id);
|
|
|
|
if (!string.IsNullOrEmpty(filterEntity.Name))
|
|
query = query.Where(m => EF.Functions.ILike(m.Name, filterEntity.Name));
|
|
|
|
if (!string.IsNullOrEmpty(filterEntity.Rank))
|
|
query = query.Where(m => EF.Functions.ILike(m.Rank, filterEntity.Rank));
|
|
|
|
if (!string.IsNullOrEmpty(filterEntity.Specialisation))
|
|
query = query.Where(m => EF.Functions.ILike(m.Specialisation, filterEntity.Specialisation));
|
|
|
|
var mages = await query.ToListAsync();
|
|
return mages;
|
|
|
|
}
|
|
|
|
public async Task<Mage> GetMageByIdAsync(Guid id)
|
|
{
|
|
var mage = await _context.Mages.FindAsync(id);
|
|
if (mage == null)
|
|
{
|
|
throw new NotFoundException($"No mage has been found with this id {id}");
|
|
}
|
|
return mage;
|
|
}
|
|
|
|
public async Task<bool> UpdateMageAsync(Mage newMageValues)
|
|
{
|
|
var mageToUpdate = await GetMageByIdAsync(newMageValues.Id);
|
|
|
|
_context.Entry(mageToUpdate).CurrentValues.SetValues(newMageValues);
|
|
|
|
foreach (var spell in newMageValues.Spells)
|
|
if (!mageToUpdate.Spells.Any(s => s.Id == spell.Id))
|
|
mageToUpdate.Spells.Add(spell);
|
|
|
|
foreach (var spell in mageToUpdate.Spells.ToList())
|
|
if (!newMageValues.Spells.Any(s => s.Id == spell.Id))
|
|
mageToUpdate.Spells.Remove(spell);
|
|
|
|
if (!_context.ChangeTracker.HasChanges()) return false;
|
|
return await _context.SaveChangesAsync() > 0;
|
|
}
|
|
}
|
|
}
|