Фикс базового репозитория

This commit is contained in:
Степанов Дмитрий 2024-04-08 07:17:17 +03:00
parent 04a6300123
commit 79929dc6d2

View File

@ -7,6 +7,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using AsbCloudApp.Exceptions;
using Microsoft.EntityFrameworkCore.ChangeTracking;
namespace AsbCloudInfrastructure.Repository
@ -120,15 +121,26 @@ namespace AsbCloudInfrastructure.Repository
{
if (!dtos.Any())
return 0;
var ids = dtos.Select(d => d.Id);
var countExistingEntities = await dbSet
.Where(d => ids.Contains(d.Id))
var ids = dtos
.Select(o => o.Id)
.Distinct()
.ToArray();
if (ids.Any(id => id == default))
throw new ArgumentInvalidException(nameof(dtos), "Все записи должны иметь Id");
if (ids.Length != dtos.Count())
throw new ArgumentInvalidException(nameof(dtos), "Все записи должны иметь уникальные Id");
var dbSet = dbContext.Set<TEntity>();
var existingEntitiesCount = await dbSet
.Where(o => ids.Contains(o.Id))
.CountAsync(token);
if (ids.Count() > countExistingEntities)
return ICrudRepository<TDto>.ErrorIdNotFound;
if (ids.Length != existingEntitiesCount)
throw new ArgumentInvalidException(nameof(dtos), "Все записи должны существовать в БД");
var entities = dtos.Select(Convert);
var entries = entities.Select(entity => dbSet.Update(entity)).Cast<EntityEntry>().ToList();
@ -145,9 +157,8 @@ namespace AsbCloudInfrastructure.Repository
.FirstOrDefault(e => e.Id == id);
if (entity == default)
return Task.FromResult(ICrudRepository<TDto>.ErrorIdNotFound);
var entry = dbSet.Remove(entity);
dbSet.Remove(entity);
var affected = dbContext.SaveChangesAsync(token);
entry.State = EntityState.Detached;
return affected;
}
@ -164,10 +175,8 @@ namespace AsbCloudInfrastructure.Repository
return ICrudRepository<TDto>.ErrorIdNotFound;
var entities = dbContext.Set<TEntity>().Where(e => ids.Contains(e.Id));
var entries = entities.Select(entity => dbSet.Remove(entity)).Cast<EntityEntry>().ToList();
var affected = await dbContext.SaveChangesAsync(token);
entries.ForEach(e => e.State = EntityState.Detached);
return affected;
dbContext.Set<TEntity>().RemoveRange(entities);
return await dbContext.SaveChangesAsync(token);
}
protected virtual TDto Convert(TEntity src) => src.Adapt<TDto>();