refactor(repository): make UpdateAsync more flexible with Action<TEntity>
- Introduced Action<TEntity>-based UpdateAsync method for more flexible updates - Updated TDto-based UpdateAsync to delegate to the new method - Reduced code duplication and Mapper dependency - Preserved existing Create, Read, and Delete functionality
This commit is contained in:
parent
5567f6731b
commit
d16a4b6bb4
@ -1,5 +1,4 @@
|
||||
using DigitalData.Core.Abstractions.Interfaces;
|
||||
using System.Linq.Expressions;
|
||||
using System.Linq.Expressions;
|
||||
#if NETFRAMEWORK
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@ -71,6 +70,16 @@ public interface IRepository<TEntity>
|
||||
public
|
||||
#endif
|
||||
Task UpdateAsync<TDto>(TDto dto, Func<IQueryable<TEntity>, IQueryable<TEntity>> query, CancellationToken cancel = default);
|
||||
|
||||
#if NET
|
||||
public
|
||||
#endif
|
||||
Task UpdateAsync(Action<TEntity> modification, Func<IQueryable<TEntity>, IQueryable<TEntity>> query, CancellationToken cancel = default);
|
||||
|
||||
#if NET
|
||||
public
|
||||
#endif
|
||||
Task UpdateAsync(Action<TEntity> modification, Expression<Func<TEntity, bool>> expression, CancellationToken cancel = default);
|
||||
#endregion Update
|
||||
|
||||
#region Delete
|
||||
|
||||
@ -87,22 +87,25 @@ public class DbRepository<TDbContext, TEntity> : IRepository<TEntity> where TDbC
|
||||
#region Update
|
||||
public virtual Task UpdateAsync<TDto>(TDto dto, Expression<Func<TEntity, bool>> expression, CancellationToken cancel = default) => UpdateAsync(dto, q => q.Where(expression), cancel);
|
||||
|
||||
public virtual async Task UpdateAsync<TDto>(TDto dto, Func<IQueryable<TEntity>, IQueryable<TEntity>> query, CancellationToken cancel = default)
|
||||
public virtual Task UpdateAsync<TDto>(TDto dto, Func<IQueryable<TEntity>, IQueryable<TEntity>> query, CancellationToken cancel = default)
|
||||
=> UpdateAsync(entity => Mapper
|
||||
#if NET
|
||||
!
|
||||
#endif
|
||||
.Map(dto, entity), query, cancel);
|
||||
|
||||
public virtual async Task UpdateAsync(Action<TEntity> modification, Func<IQueryable<TEntity>, IQueryable<TEntity>> query, CancellationToken cancel = default)
|
||||
{
|
||||
var entities = await query(Entities).ToListAsync(cancel);
|
||||
|
||||
for (int i = entities.Count - 1; i >= 0; i--)
|
||||
{
|
||||
Mapper
|
||||
#if NET
|
||||
!
|
||||
#endif
|
||||
.Map(dto, entities[i]);
|
||||
Entities.Update(entities[i]);
|
||||
}
|
||||
modification.Invoke(entities[i]);
|
||||
|
||||
await Context.SaveChangesAsync(cancel);
|
||||
}
|
||||
|
||||
public virtual Task UpdateAsync(Action<TEntity> modification, Expression<Func<TEntity, bool>> expression, CancellationToken cancel = default)
|
||||
=> UpdateAsync(modification, q => q.Where(expression), cancel);
|
||||
#endregion Update
|
||||
|
||||
#region Delete
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user