improvements, fixes, etc...

This commit is contained in:
Loretta 2024-06-30 15:34:19 +02:00
parent e20608ade9
commit c393ea325c
2 changed files with 31 additions and 0 deletions

View File

@ -86,6 +86,12 @@ public abstract class AcDalBase<TDbContext> : IAcDalBase<TDbContext> where TDbCo
public bool Transaction(Func<TDbContext, bool> callbackTransactionBody, bool throwException = false)
=> this.Transaction<TDbContext>(callbackTransactionBody, throwException);
public Task<TEntity?> UpdateSafeAsync<TEntity>(TEntity entity, Func<TDbContext, TEntity, bool>? callbackTransactionBody = null, bool throwException = false) where TEntity : class, IEntityGuid
=> this.UpdateSafeAsync<TDbContext, TEntity>(entity, callbackTransactionBody, throwException);
public TEntity? UpdateSafe<TEntity>(TEntity entity, Func<TDbContext, TEntity, bool>? callbackTransactionBody = null, bool throwException = false) where TEntity : class, IEntityGuid
=> this.UpdateSafe<TDbContext, TEntity>(entity, callbackTransactionBody, throwException);
public override string ToString()
{
return Name;

View File

@ -3,6 +3,7 @@ using AyCode.Database.DataLayers;
using AyCode.Database.DbContexts;
using AyCode.Interfaces.Entities;
using AyCode.Utils.Extensions;
using Microsoft.EntityFrameworkCore;
namespace AyCode.Database.Extensions;
@ -46,4 +47,28 @@ public static class AcDalExtension
return acDal.Context.Transaction(callbackTransactionBody, throwException);
}
}
public static Task<TEntity?> UpdateSafeAsync<TDbContext, TEntity>(this IAcDalBase<TDbContext> acDal, TEntity entity, Func<TDbContext, TEntity, bool>? callbackTransactionBody = null, bool throwException = false) where TDbContext : AcDbContextBase where TEntity : class, IEntityGuid
=> TaskHelper.ToThreadPoolTask(() => acDal.UpdateSafe(entity, callbackTransactionBody, throwException));
public static TEntity? UpdateSafe<TDbContext, TEntity>(this IAcDalBase<TDbContext> acDal, TEntity entity, Func<TDbContext, TEntity, bool>? callbackTransactionBody = null, bool throwException = false) where TDbContext : AcDbContextBase where TEntity : class, IEntityGuid
{
TEntity? updateEntity = null;
var isSuccess = acDal.Context.Transaction(ctx =>
{
updateEntity = ctx.Set<TEntity>().FirstOrDefault(x => x.Id == entity.Id);
if (updateEntity == null) return false;
//ctx.Entry(updateEntity).State = EntityState.Detached;
ctx.Entry(updateEntity).CurrentValues.SetValues(entity);
if (callbackTransactionBody == null)
return ctx.Update(updateEntity).State == EntityState.Modified;
return callbackTransactionBody.Invoke(ctx, updateEntity);
}, throwException);
return isSuccess ? updateEntity : null;
}
}