Files
lux/EgwCoreLib.Lux.Data/Repository/Utils/GenValRepository.cs
T

115 lines
3.7 KiB
C#

using EgwCoreLib.Lux.Data.DbModel.Utils;
using Microsoft.EntityFrameworkCore;
namespace EgwCoreLib.Lux.Data.Repository.Utils
{
public class GenValRepository : BaseRepository, IGenValRepository
{
#region Public Constructors
public GenValRepository(DataLayerContext db) : base(db)
{
}
#endregion Public Constructors
#region Public Methods
public void Add(GenValueModel entity) => _dbCtx.DbSetGenVal.Add(entity);
public async Task<bool> DeleteAsync(GenValueModel rec2del)
{
// 1. Recupero il record da eliminare
var dbResult = await _dbCtx.DbSetGenVal
.FirstOrDefaultAsync(x => x.GenValID == rec2del.GenValID);
if (dbResult == null)
return false;
// 2. Recupero i record successivi da shiftare
var list2Move = await _dbCtx.DbSetGenVal
.Where(x => x.ClassCod == rec2del.ClassCod && x.Index > dbResult.Index)
.ToListAsync();
foreach (var item in list2Move)
{
item.Index--;
_dbCtx.Entry(item).State = EntityState.Modified;
}
// 3. Rimuovo il record
_dbCtx.DbSetGenVal.Remove(dbResult);
// 4. Salvo tutto
return await _dbCtx.SaveChangesAsync() > 0;
}
public async Task<GenValueModel?> GetByIdAsync(int Id) =>
await _dbCtx.DbSetGenVal.FirstOrDefaultAsync(x => x.GenValID == Id);
public async Task<List<GenValueModel>> GetFiltAsync(string codClass)
{
return await _dbCtx.DbSetGenVal
.Where(x => x.ClassCod == codClass)
.AsNoTracking()
.ToListAsync();
}
public async Task<bool> MoveAsync(GenValueModel selRec, bool moveUp)
{
// 1. Recupero il record corrente
var currRec = await _dbCtx.DbSetGenVal
.FirstOrDefaultAsync(x => x.GenValID == selRec.GenValID);
if (currRec == null)
return false;
// 2. Numero totale record della classe
int numRec = await _dbCtx.DbSetGenVal
.CountAsync(x => x.ClassCod == selRec.ClassCod);
// 3. Calcolo nuova posizione
int newPos = moveUp ? currRec.Index - 1 : currRec.Index + 1;
bool canMove = moveUp ? newPos > 0 : newPos <= numRec;
if (!canMove)
return false;
// 4. Recupero il record da scambiare
var otherRec = await _dbCtx.DbSetGenVal
.FirstOrDefaultAsync(x => x.ClassCod == selRec.ClassCod && x.Index == newPos);
if (otherRec == null)
return false;
// 5. Swap indici
otherRec.Index = currRec.Index;
currRec.Index = newPos;
_dbCtx.Entry(otherRec).State = EntityState.Modified;
_dbCtx.Entry(currRec).State = EntityState.Modified;
// 6. Salvo
return await _dbCtx.SaveChangesAsync() > 0;
}
public void Update(GenValueModel entity)
{
// Recuperiamo l'entità tracciata dal context
var trackedEntity = _dbCtx.DbSetGenVal.Local.FirstOrDefault(x => x.GenValID == entity.GenValID);
if (trackedEntity != null)
{
// Aggiorna i valori dell'entità tracciata con quelli della nuova
_dbCtx.Entry(trackedEntity).CurrentValues.SetValues(entity);
}
else
{
_dbCtx.DbSetGenVal.Update(entity);
}
}
#endregion Public Methods
}
}