forked from ddrilling/AsbCloudServer
70 lines
2.4 KiB
C#
70 lines
2.4 KiB
C#
|
using AsbCloudApp.Data;
|
|||
|
using AsbCloudApp.Repositories;
|
|||
|
using AsbCloudApp.Requests;
|
|||
|
using System.Collections.Generic;
|
|||
|
using System.Threading.Tasks;
|
|||
|
using System.Threading;
|
|||
|
using System.Linq;
|
|||
|
using System.ComponentModel.DataAnnotations;
|
|||
|
using AsbCloudApp.Exceptions;
|
|||
|
|
|||
|
namespace AsbCloudApp.Services
|
|||
|
{
|
|||
|
/// <summary>
|
|||
|
///
|
|||
|
/// </summary>
|
|||
|
/// <typeparam name="TDto"></typeparam>
|
|||
|
/// <typeparam name="TRequest"></typeparam>
|
|||
|
public abstract class ChangeLogServiceAbstract<TDto, TRequest>
|
|||
|
where TDto : ChangeLogAbstract
|
|||
|
where TRequest : ChangeLogBaseRequest
|
|||
|
{
|
|||
|
/// <summary>
|
|||
|
/// Репозиторий
|
|||
|
/// </summary>
|
|||
|
public IChangeLogRepository<TDto, TRequest> repository { get; }
|
|||
|
|
|||
|
/// <summary>
|
|||
|
/// ctor
|
|||
|
/// </summary>
|
|||
|
/// <param name="repository"></param>
|
|||
|
public ChangeLogServiceAbstract(IChangeLogRepository<TDto, TRequest> repository)
|
|||
|
{
|
|||
|
this.repository = repository;
|
|||
|
}
|
|||
|
|
|||
|
/// <summary>
|
|||
|
/// Добавляет Dto у которых id == 0, изменяет dto у которых id != 0
|
|||
|
/// </summary>
|
|||
|
/// <param name="idUser"></param>
|
|||
|
/// <param name="dtos"></param>
|
|||
|
/// <param name="token"></param>
|
|||
|
/// <returns></returns>
|
|||
|
public virtual async Task<int> UpdateOrInsertRange(int idUser, IEnumerable<TDto> dtos, CancellationToken token)
|
|||
|
{
|
|||
|
var validationResults = Validate(dtos);
|
|||
|
if (validationResults.Any())
|
|||
|
{
|
|||
|
var errors = validationResults.SelectMany(r => r.MemberNames.Select(member => $"{member}: {r.ErrorMessage}"));
|
|||
|
throw new ArgumentInvalidException(nameof(dtos), $"not valid: {string.Join("\n", errors)}");
|
|||
|
}
|
|||
|
|
|||
|
var itemsToInsert = dtos.Where(e => e.Id == 0);
|
|||
|
var itemsToUpdate = dtos.Where(e => e.Id != 0);
|
|||
|
|
|||
|
var result = await repository.InsertRange(idUser, itemsToInsert, token);
|
|||
|
result += await repository.UpdateRange(idUser, itemsToInsert, token);
|
|||
|
|
|||
|
return result;
|
|||
|
}
|
|||
|
|
|||
|
/// <summary>
|
|||
|
/// Валидация входных данных
|
|||
|
/// </summary>
|
|||
|
/// <param name="dtos"></param>
|
|||
|
/// <returns></returns>
|
|||
|
protected virtual IEnumerable<ValidationResult> Validate(IEnumerable<TDto> dtos)
|
|||
|
=> Enumerable.Empty<ValidationResult>();
|
|||
|
}
|
|||
|
}
|