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 { /// /// /// /// /// public abstract class ChangeLogServiceAbstract where TDto : ChangeLogAbstract where TRequest : ChangeLogBaseRequest { /// /// Репозиторий /// public IChangeLogRepository repository { get; } /// /// ctor /// /// public ChangeLogServiceAbstract(IChangeLogRepository repository) { this.repository = repository; } /// /// Добавляет Dto у которых id == 0, изменяет dto у которых id != 0 /// /// /// /// /// public virtual async Task UpdateOrInsertRange(int idUser, IEnumerable 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; } /// /// Валидация входных данных /// /// /// protected virtual IEnumerable Validate(IEnumerable dtos) => Enumerable.Empty(); } }