优化上传代码

This commit is contained in:
2022-05-29 17:46:14 +08:00
parent ae70c7f69b
commit 5d96df5d00
26 changed files with 1567 additions and 2361 deletions
@@ -14,6 +14,7 @@ using System.Threading.Tasks;
using EFCore.BulkExtensions;
using IRaCIS.Core.Domain.Share;
using IRaCIS.Core.Infra.EFCore.Common.Dto;
using System.Reflection;
namespace IRaCIS.Core.Infra.EFCore
{
@@ -88,6 +89,10 @@ namespace IRaCIS.Core.Infra.EFCore
Task<bool> BatchDeleteAsync<T>(Expression<Func<T, bool>> deleteFilter) where T : Entity;
Task<bool> BatchUpdateAsync<T>(Expression<Func<T, bool>> where, Expression<Func<T, T>> updateFactory) where T : Entity;
Task UpdatePartialFromQueryAsync<T>(Expression<Func<T, bool>> updateFilter,
Expression<Func<T, T>> updateFactory,
bool autoSave = false, bool ignoreQueryFilter = false) where T : Entity;
}
public class Repository : IRepository
@@ -493,6 +498,62 @@ namespace IRaCIS.Core.Infra.EFCore
return await _dbContext.Set<T>().AsNoTracking().IgnoreQueryFilters().Where(whereFilter).BatchUpdateAsync(updateFactory).ConfigureAwait(false) > 0;
}
public async Task UpdatePartialFromQueryAsync<T>(Expression<Func<T, bool>> updateFilter,
Expression<Func<T, T>> updateFactory,
bool autoSave = false, bool ignoreQueryFilter = false) where T : Entity
{
if (updateFilter == null)
{
throw new ArgumentException("更新过滤条件不允许为空", nameof(updateFilter));
}
var query = ignoreQueryFilter ? _dbContext.Set<T>().AsNoTracking().IgnoreQueryFilters() : _dbContext.Set<T>().AsNoTracking();
var searchEntityList = await query.Where(updateFilter).ToListAsync();
foreach (var needUpdateEntity in searchEntityList)
{
await UpdateAsync(needUpdateEntity, updateFactory, autoSave);
}
}
public async Task<bool> UpdateAsync<T>(T waitModifyEntity, Expression<Func<T, T>> updateFactory, bool autoSave = false) where T : Entity
{
var entityEntry = _dbContext.Entry(waitModifyEntity);
entityEntry.State = EntityState.Detached;
ModifyPartialFiled(waitModifyEntity, updateFactory);
return await SaveChangesAsync(autoSave);
}
/// <summary>更新后拥有完整的实体信息,便于稽查</summary>
private void ModifyPartialFiled<T>(T waitModifyEntity, Expression<Func<T, T>> updateFactory)
{
List<PropertyInfo> list = ((MemberInitExpression)updateFactory.Body).Bindings.Select(mb => mb.Member.Name)
.Select(propName => typeof(T).GetProperty(propName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)).ToList();
Func<T, T> func = updateFactory.Compile();
T applyObj = func(waitModifyEntity);
//深拷贝更新之前实体信息
//var copyObj = waitModifyEntity.Clone();
foreach (PropertyInfo prop in list)
{
object value = prop.GetValue(applyObj);
prop.SetValue(waitModifyEntity, value);
_dbContext.Entry(waitModifyEntity).Property(prop.Name).IsModified = true;
}
}
}
#endregion