public async Task <EntityOperationResult <AgeCategory> > EditAsync(AgeCategoryDto editDto) { string errors = CheckBeforeModification(editDto, false); if (!string.IsNullOrEmpty(errors)) { return(EntityOperationResult <AgeCategory> .Failure().AddError(errors)); } try { var value = await repositoryBaseId.GetByIdAsync(editDto.Id); value.AgeBegin = editDto.AgeBegin; value.AgeEnd = editDto.AgeEnd; repositoryBaseId.Update(value); await repositoryBaseId.SaveAsync(); return(EntityOperationResult <AgeCategory> .Success(value)); } catch (Exception ex) { return(EntityOperationResult <AgeCategory> .Failure().AddError(ex.Message)); } }
public async Task <EntityOperationResult <TBase> > CreateItemAsync(TDto basketCreateDto) { string errors = CheckAndGetErrors(basketCreateDto); if (!string.IsNullOrEmpty(errors)) { return(EntityOperationResult <TBase> .Failure().AddError(errors)); } using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { try { TBase value = _mapper.Map <TBase>(basketCreateDto); var entity = await unitOfWork.GetRepository <TBase>().AddAsync(value); await unitOfWork.CompleteAsync(); return(EntityOperationResult <TBase> .Success(entity)); } catch (Exception ex) { return(EntityOperationResult <TBase> .Failure().AddError(ex.Message)); } } }
public async Task <EntityOperationResult <TBase> > DeleteItemAsync(int id) { using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { try { TBase value = unitOfWork.GetRepository <TBase>().GetById(id); if (value == null) { return(EntityOperationResult <TBase> .Failure().AddError("Не найдена запись")); } string error = CkeckBefforDelet(value); if (!string.IsNullOrEmpty(error)) { return(EntityOperationResult <TBase> .Failure().AddError(error)); } unitOfWork.GetRepository <TBase>().Delete(value); await unitOfWork.CompleteAsync(); return(EntityOperationResult <TBase> .Success(value)); } catch (Exception ex) { return(EntityOperationResult <TBase> .Failure().AddError(ex.Message)); } } }
public async Task <EntityOperationResult <Project> > DeleteItemAsync(ProjectDto projectDeleteDto) { using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { var project = unitOfWork.Project.GetById(projectDeleteDto.Id); if (project.ProjectUsers.Any(x => projectDeleteDto.ProjectTasks.Count > 0)) { return(EntityOperationResult <Project> .Failure() .AddError($"Есть задания удалите сперва их")); } try { SetProjectIdToList(project.ProjectUsers, project.Id); unitOfWork.Project.UpdateProjectUsers(null, project.ProjectUsers); unitOfWork.Project.Delete(project); await unitOfWork.CompleteAsync(); return(EntityOperationResult <Project> .Success(project)); } catch (Exception ex) { return(EntityOperationResult <Project> .Failure().AddError(ex.Message)); } } }
public async Task <EntityOperationResult <Language> > EditItemAsync(LanguageDto basketEditDto) { string errors = CheckAndGetErrors(basketEditDto, false); if (!string.IsNullOrEmpty(errors)) { return(EntityOperationResult <Language> .Failure().AddError(errors)); } using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { try { var language = unitOfWork.Language.GetById(basketEditDto.Id); if (language == null) { return(EntityOperationResult <Language> .Failure().AddError("Не найдена запись")); } language.Name = basketEditDto.Name; unitOfWork.Language.Update(language); await unitOfWork.CompleteAsync(); return(EntityOperationResult <Language> .Success(language)); } catch (Exception ex) { return(EntityOperationResult <Language> .Failure().AddError(ex.Message)); } } }
public virtual async Task <EntityOperationResult <TDto> > CreateAsync(TDtoCreate createDto) { string errors = CheckBeforeModification(createDto); if (!string.IsNullOrEmpty(errors)) { return(EntityOperationResult <TDto> .Failure().AddError(errors)); } try { TEntity value = mapper.Map <TEntity>(createDto); var entity = await repositoryBase.AddAsync(value); await repositoryBase.SaveAsync(); var dto = mapper.Map <TDto>(entity); return(EntityOperationResult <TDto> .Success(dto)); } catch (Exception ex) { return(EntityOperationResult <TDto> .Failure().AddError(ex.Message)); } }
public async Task <EntityOperationResult <Dish> > DeleeteItemAsync(DishDeleteDto deleteDto, string path) { using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { try { var dish = unitOfWork.Dish.GetById(deleteDto.Id); unitOfWork.Dish.Delete(dish); await unitOfWork.CompleteAsync(); if (dish.PictureName?.Length > 0) { FileService fileService = new FileService(null, path + "\\" + dish.PictureName, string.Empty, dish.PictureFormat); fileService.AddOrDelete(true); } return(EntityOperationResult <Dish> .Success(dish)); } catch (Exception ex) { return(EntityOperationResult <Dish> .Failure().AddError(ex.Message)); } } }
private EntityOperationResult <Project> Check(ProjectDto project) { if (project.Name == string.Empty) { return(EntityOperationResult <Project> .Failure() .AddError("Не указано наименование")); } if (project.ContractorCompany == string.Empty) { return(EntityOperationResult <Project> .Failure() .AddError("Не указано наименование компании-исполнителя")); } if (project.CustomerCompany == string.Empty) { return(EntityOperationResult <Project> .Failure() .AddError("Не указано наименование компании-заказчика")); } if (project.DateBegin == null || project.DateEnd == null) { return(EntityOperationResult <Project> .Failure() .AddError("Не указан период")); } if (project.SupervisorUser == null) { return(EntityOperationResult <Project> .Failure() .AddError("Не указаны руководитель проекта")); } return(null); }
public async Task <EntityOperationResult <ProjectTask> > EditItemAsync(ProjectTaskDto projectTaskEditDto) { using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { var result = Check(projectTaskEditDto); if (result != null) { return(result); } var projectTask = unitOfWork.ProjectTask.GetById(projectTaskEditDto.Id); try { projectTask.Name = projectTaskEditDto.Name; projectTask.AuthorId = projectTaskEditDto.Author.Id; projectTask.ExecutorId = projectTaskEditDto.Executor.Id; projectTask.Status = (int)projectTaskEditDto.Status; projectTask.ProjectId = projectTaskEditDto.Project.Id; projectTask.Priority = projectTaskEditDto.Priority; projectTask.Comment = projectTaskEditDto.Comment; unitOfWork.ProjectTask.Update(projectTask); await unitOfWork.CompleteAsync(); return(EntityOperationResult <ProjectTask> .Success(projectTask)); } catch (Exception ex) { return(EntityOperationResult <ProjectTask> .Failure().AddError(ex.Message)); } } }
public async Task <EntityOperationResult <Author> > EditAsync(AuthorDto editDto) { string errors = CheckBeforeModification(editDto, false); if (!string.IsNullOrEmpty(errors)) { return(EntityOperationResult <Author> .Failure().AddError(errors)); } try { var value = await repositoryBaseId.GetByIdAsync(editDto.Id); value.FirstName = editDto.FirstName; value.MiddleName = editDto.MiddleName; value.SurName = editDto.SurName; repositoryBaseId.Update(value); await repositoryBaseId.SaveAsync(); return(EntityOperationResult <Author> .Success(value)); } catch (Exception ex) { return(EntityOperationResult <Author> .Failure().AddError(ex.Message)); } }
public async Task <EntityOperationResult <Organization> > DeleeteItemAsync(OrganizationDeleteDto deleteDto, string path) { using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { if (unitOfWork.Organization.IsHasDishesh(deleteDto.Id)) { return(EntityOperationResult <Organization> .Failure() .AddError($"Кафе с именем {deleteDto.Name} имеет блюда")); } try { var organization = unitOfWork.Organization.GetById(deleteDto.Id); FileService fileService = new FileService(null, path + "/Org/\\" + organization.PictureName, string.Empty, organization.PictureFormat); fileService.AddOrDelete(true); unitOfWork.Organization.Delete(organization); await unitOfWork.CompleteAsync(); return(EntityOperationResult <Organization> .Success(organization)); } catch (Exception ex) { return(EntityOperationResult <Organization> .Failure().AddError(ex.Message)); } } }
public async Task <EntityOperationResult <TBase> > CreateItemAsync(TDto basketCreateDto) { // Валидацию модели можно сделать через атрибуты валидации, которые ты вешаешь на свойства класса. // Взывать проверку на основе атрибутов можно своим кодом. Я уже такой писал: // https://github.com/maximgorbatyuk/net-blank-app/blob/master/src/Utils/Validators/EntityValidator.cs string errors = CheckAndGetErrors(basketCreateDto); if (!string.IsNullOrEmpty(errors)) { return(EntityOperationResult <TBase> .Failure().AddError(errors)); } using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { try { TBase value = _mapper.Map <TBase>(basketCreateDto); var entity = await unitOfWork.GetRepository <TBase>().AddAsync(value); await unitOfWork.CompleteAsync(); return(EntityOperationResult <TBase> .Success(entity)); } catch (Exception ex) { // Если ты хочешь использовать подход с классом-прокси EntityOperationResult, // То я бы сохранял и передавал выше еще и сам объект ex, потому что в эксепшене важно не только месседж, // но и стектрейс, и дополнительная инфа, и тип класса исключения. // Но я бы отказался от такого прокси-класса и пробрасывал бы исключение наверх дальше, даже // не отлавливая его здесь. // Исключения ты отлавливаешь в одной точке - в созданной специально для этого middleware. // а узнать, что это такое, ты можешь либо из нашего курса, либо на сайте metanit.com return(EntityOperationResult <TBase> .Failure().AddError(ex.Message)); } } }
public async Task <EntityOperationResult <TBase> > DeleteItemAsync(List <int> idList) { using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { try { if (idList == null || idList.Count == 0) { return(EntityOperationResult <TBase> .Failure().AddError("Не задан лист с id")); } List <TBase> listVal = await unitOfWork.GetRepository <TBase>().GetAllOfIdAsync(idList); if (listVal == null || listVal.Count == 0) { return(EntityOperationResult <TBase> .Failure().AddError("Не найдена запись")); } string error = CkeckBefforDeleteList(listVal); if (!string.IsNullOrEmpty(error)) { return(EntityOperationResult <TBase> .Failure().AddError(error)); } unitOfWork.GetRepository <TBase>().DeleteALot(listVal); await unitOfWork.CompleteAsync(); return(EntityOperationResult <TBase> .Success(listVal[0])); } catch (Exception ex) { return(EntityOperationResult <TBase> .Failure().AddError(ex.Message)); } } }
public async Task <EntityOperationResult <Project> > EditItemAsync(ProjectDto projectEditDto) { using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { var result = Check(projectEditDto); if (result != null) { return(result); } var project = unitOfWork.Project.GetById(projectEditDto.Id); for (int i = 0; i < projectEditDto.ProjectUsers.Count; i++) { if (projectEditDto.ProjectUsers[i].Status == ProjectUserStatus.New) { if (project.ProjectUsers.Count(x => x.UserId == projectEditDto.ProjectUsers[i].Id) > 0) { return(EntityOperationResult <Project> .Failure() .AddError($"Пользователь {projectEditDto.ProjectUsers[i].Name} уже есть в базе")); } } } try { GetProjectDtoToProject(projectEditDto, project); unitOfWork.Project.Update(project); await unitOfWork.CompleteAsync(); var projectUserList = Mapper.Map <List <ProjectUser> >(projectEditDto.ProjectUsers .Where(x => x.Status == ProjectUserStatus.New) .ToList()); SetProjectIdToList(projectUserList, project.Id); List <int> deleteList = projectEditDto.ProjectUsers .Where(x => x.Status == ProjectUserStatus.Delete) .Select(x => x.Id).ToList(); var projectUserDeleteList = new List <ProjectUser>(); if (deleteList?.Count > 0) { projectUserDeleteList = project.ProjectUsers .Where(y => deleteList.Any(x => x == y.Id)).ToList(); } SetProjectIdToList(projectUserDeleteList, project.Id); unitOfWork.Project.UpdateProjectUsers(projectUserList, projectUserDeleteList); await unitOfWork.CompleteAsync(); return(EntityOperationResult <Project> .Success(project)); } catch (Exception ex) { return(EntityOperationResult <Project> .Failure().AddError(ex.Message)); } } }
public async Task <EntityOperationResult <T> > UpdateAsync(TDto dto) { try { T value = mapper.Map <T>(dto); repositoryBase.Update(value); return(EntityOperationResult <T> .Success(value)); } catch (Exception ex) { return(EntityOperationResult <T> .Failure().AddError(ex.Message)); } }
public override async Task <EntityOperationResult <AuthorDto> > GetByIdDeteilsAsync(Guid id) { try { var entity = await authorRepository.GetByIdAsync(id, GetOptionsForDeteils()); var dto = mapper.Map <AuthorDto>(entity); return(EntityOperationResult <AuthorDto> .Success(dto)); } catch (Exception ex) { return(EntityOperationResult <AuthorDto> .Failure().AddError(ex.Message)); } }
public async Task <EntityOperationResult <Dish> > EditItemAsync(DishEditDto editDto, string path) { using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { if (unitOfWork.Dish.IsExistByNAme(editDto.Id, editDto.Name, editDto.OrganizationId)) { return(EntityOperationResult <Dish> .Failure() .AddError($"Блюдо с именем {editDto.Name} уже существует")); } if (editDto.Price <= 0) { return(EntityOperationResult <Dish> .Failure() .AddError("Цена не может быть меньше или равняться нулю")); } try { var dish = unitOfWork.Dish.GetById(editDto.Id); string oldPictureFormat = dish.PictureFormat; var fileService = new FileService(editDto.File, path + "\\" + dish.PictureName, editDto.PictureName, dish.PictureFormat); dish.Name = editDto.Name; dish.Price = editDto.Price; if (editDto.File?.Length > 0 && !editDto.IsPictureDelete) { dish.PictureFormat = fileService.GetTypeFile(); } else if (editDto.IsPictureDelete) { dish.PictureFormat = string.Empty; } dish.Comment = editDto.Comment; unitOfWork.Dish.Update(dish); await unitOfWork.CompleteAsync(); fileService.AddOrDelete(editDto.IsPictureDelete); return(EntityOperationResult <Dish> .Success(dish)); } catch (Exception ex) { return(EntityOperationResult <Dish> .Failure().AddError(ex.Message)); } } }
public async Task <EntityOperationResult <Dish> > CreateItemAsync(DishCreateDto createDto, string path) { using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { if (unitOfWork.Dish.IsExistByNAme(createDto.Name, createDto.OrganizationId)) { return(EntityOperationResult <Dish> .Failure() .AddError($"Блюдо с именем {createDto.Name} уже существует")); } if (createDto.Price <= 0) { return(EntityOperationResult <Dish> .Failure() .AddError("Цена не может быть меньше или равняться нулю")); } try { var dish = new Dish { Name = createDto.Name, OrganizationId = createDto.OrganizationId, Price = createDto.Price, PictureName = System.Guid.NewGuid().ToString(), Comment = createDto.Comment }; var fileService = new FileService(createDto.File, path + "\\" + dish.PictureName, createDto.PictureName); dish.PictureFormat = fileService.GetTypeFile(); var entity = await unitOfWork.Dish.AddAsync(dish); await unitOfWork.CompleteAsync(); fileService.Add(); return(EntityOperationResult <Dish> .Success(entity)); } catch (Exception ex) { return(EntityOperationResult <Dish> .Failure().AddError(ex.Message)); } } }
public async Task <EntityOperationResult <Basket> > DeleteItemAsync(BasketDeleteDto basketDeleteDto) { using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { try { var basket = unitOfWork.Basket.GetById(basketDeleteDto.Id); unitOfWork.Basket.Delete(basket); await unitOfWork.CompleteAsync(); return(EntityOperationResult <Basket> .Success(basket)); } catch (Exception ex) { return(EntityOperationResult <Basket> .Failure().AddError(ex.Message)); } } }
public async Task <EntityOperationResult <ProjectTask> > DeleteItemAsync(ProjectTaskDto projectTDtoDeleteDto) { using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { var projectTask = unitOfWork.ProjectTask.GetById(projectTDtoDeleteDto.Id); try { unitOfWork.ProjectTask.Delete(projectTask); await unitOfWork.CompleteAsync(); return(EntityOperationResult <ProjectTask> .Success(projectTask)); } catch (Exception ex) { return(EntityOperationResult <ProjectTask> .Failure().AddError(ex.Message)); } } }
public async Task <EntityOperationResult <Organization> > EditItemAsync(OrganizationEditDto editDto, string path) { using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { if (unitOfWork.Organization.IsExistByNAme(editDto.Id, editDto.Name)) { return(EntityOperationResult <Organization> .Failure() .AddError($"Кафе с именем {editDto.Name} уже существует")); } try { var organization = unitOfWork.Organization.GetById(editDto.Id); string oldPictureFormat = organization.PictureFormat; var fileService = new FileService(editDto.File, path + "\\" + organization.PictureName, editDto.PictureName, organization.PictureFormat); organization.Name = editDto.Name; if (editDto.File?.Length > 0 && !editDto.IsPictureDelete) { organization.PictureFormat = fileService.GetTypeFile(); } else if (editDto.IsPictureDelete) { organization.PictureFormat = string.Empty; } organization.Comment = editDto.Comment; unitOfWork.Organization.Update(organization); await unitOfWork.CompleteAsync(); fileService.AddOrDelete(editDto.IsPictureDelete); return(EntityOperationResult <Organization> .Success(organization)); } catch (Exception ex) { return(EntityOperationResult <Organization> .Failure().AddError(ex.Message)); } } }
public async Task <EntityOperationResult <Basket> > PayItemAsync(BasketPayDto basketPayDto) { using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { try { var basket = unitOfWork.Basket.GetById(basketPayDto.Id); basket.DateAction = DateTime.Now; basket.Status = true; unitOfWork.Basket.Update(basket); await unitOfWork.CompleteAsync(); return(EntityOperationResult <Basket> .Success(basket)); } catch (Exception ex) { return(EntityOperationResult <Basket> .Failure().AddError(ex.Message)); } } }
public EntityOperationResult <SendMessageDto> Send(IEmailService emailSender, SendMessageDto sendMessage) { if (!sendMessage.IsSend) { return(EntityOperationResult <SendMessageDto> .Failure().AddError("Не была отмечана галочка отправить письма")); } try { var userInfoDtos = sendMessage.UserList.Where(x => x.IsSend).ToList(); foreach (var user in userInfoDtos) { emailSender.SendEmailMesage(user, sendMessage.Topic, sendMessage.Message); } return(EntityOperationResult <SendMessageDto> .Success(new SendMessageDto())); } catch (Exception ex) { return(EntityOperationResult <SendMessageDto> .Failure().AddError(ex.Message)); } }
public async Task <EntityOperationResult <ProjectTask> > CreateItemAsync(ProjectTaskDto projectTaskCreateDto) { using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { var result = Check(projectTaskCreateDto); if (result != null) { return(result); } if (projectTaskCreateDto.Project == null) { return(EntityOperationResult <ProjectTask> .Failure() .AddError("Не указан Проект")); } try { var project = new ProjectTask { Name = projectTaskCreateDto.Name, AuthorId = projectTaskCreateDto.Author.Id, ExecutorId = projectTaskCreateDto.Executor.Id, Status = (int)projectTaskCreateDto.Status, ProjectId = projectTaskCreateDto.Project.Id, Priority = projectTaskCreateDto.Priority, Comment = projectTaskCreateDto.Comment }; var entity = await unitOfWork.ProjectTask.AddAsync(project); await unitOfWork.CompleteAsync(); return(EntityOperationResult <ProjectTask> .Success(entity)); } catch (Exception ex) { return(EntityOperationResult <ProjectTask> .Failure().AddError(ex.Message)); } } }
public async Task <EntityOperationResult <Project> > CreateItemAsync(ProjectDto projectCreateDto) { using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { var result = Check(projectCreateDto); if (result != null) { return(result); } if (projectCreateDto.ProjectUsers == null || projectCreateDto.ProjectUsers.Count == 0) { return(EntityOperationResult <Project> .Failure() .AddError("Не указаны исполнители")); } try { var project = new Project(); GetProjectDtoToProject(projectCreateDto, project); var entity = await unitOfWork.Project.AddAsync(project); await unitOfWork.CompleteAsync(); var projectUserList = Mapper.Map <List <ProjectUser> >(projectCreateDto.ProjectUsers .Where(x => x.Status == ProjectUserStatus.New) .ToList()); SetProjectIdToList(projectUserList, entity.Id); unitOfWork.Project.UpdateProjectUsers(projectUserList); await unitOfWork.CompleteAsync(); return(EntityOperationResult <Project> .Success(entity)); } catch (Exception ex) { return(EntityOperationResult <Project> .Failure().AddError(ex.Message)); } } }
public override async Task <EntityOperationResult <SkillOfLevelDto> > CreateAsync(SkillOfLevelEditDto createDto) { string errors = CheckBeforeModification(createDto); if (!string.IsNullOrEmpty(errors)) { return(EntityOperationResult <SkillOfLevelDto> .Failure().AddError(errors)); } try { var skill = new Skill { Name = createDto.Name, }; skill = await skillRepository.AddAsync(skill); await skillRepository.SaveAsync(); SkillOfLevel entity = null; for (byte i = createDto.StartLevel; i <= createDto.EndLevel; i++) { entity = await repositoryBase.AddAsync(new SkillOfLevel { Level = i, SkillId = skill.Id, }); } await repositoryBase.SaveAsync(); var dto = mapper.Map <SkillOfLevelDto>(entity); return(EntityOperationResult <SkillOfLevelDto> .Success(dto)); } catch (Exception ex) { return(EntityOperationResult <SkillOfLevelDto> .Failure().AddError(ex.Message)); } }
public EntityOperationResult <InportExcelDto> Analysis(InportExcelDto value) { try { if (value.File == null || value.File.Length == 0) { return(EntityOperationResult <InportExcelDto> .Failure().AddError("Вы не выбрали файл")); } using (var stream = new MemoryStream(value.File)) { //await formFile.CopyToAsync(stream, cancellationToken); using (var package = new ExcelPackage(stream)) { ExcelWorksheet worksheet = package.Workbook.Worksheets[0]; var rowCount = worksheet.Dimension.Rows; //var colCount = worksheet.Dimension.Columns; int age = 0; for (int row = 2; row <= rowCount; row++) { age = 0; int.TryParse(worksheet.Cells[row, 4]?.Value?.ToString().Trim() ?? string.Empty, out age); _messageToUserList.Add(new UserInfoDto { Name = worksheet.Cells[row, 1]?.Value?.ToString().Trim() ?? string.Empty, SurName = worksheet.Cells[row, 2]?.Value?.ToString().Trim() ?? string.Empty, EMail = worksheet.Cells[row, 3]?.Value?.ToString().Trim() ?? string.Empty, Age = age, }); } } } return(EntityOperationResult <InportExcelDto> .Success(new InportExcelDto())); } catch (Exception ex) { return(EntityOperationResult <InportExcelDto> .Failure().AddError(ex.Message)); } }
private EntityOperationResult <ProjectTask> Check(ProjectTaskDto projectTask) { if (projectTask.Name == string.Empty) { return(EntityOperationResult <ProjectTask> .Failure() .AddError("Не указано наименование")); } if (projectTask.Author == null) { return(EntityOperationResult <ProjectTask> .Failure() .AddError("Не указан Автор")); } if (projectTask.Executor == null) { return(EntityOperationResult <ProjectTask> .Failure() .AddError("Не указан Исполнитель")); } return(null); }
public async Task <EntityOperationResult <Organization> > CreateItemAsync(OrganizationCreateDto createDto, string path) { using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { if (unitOfWork.Organization.IsExistByNAme(createDto.Name)) { return(EntityOperationResult <Organization> .Failure() .AddError($"Кафе с именем {createDto.Name} уже существует")); } try { var organization = new Organization { Name = createDto.Name, PictureName = System.Guid.NewGuid().ToString(), Comment = createDto.Comment, }; var fileService = new FileService(createDto.File, path + "\\" + organization.PictureName, createDto.PictureName); organization.PictureFormat = fileService.GetTypeFile(); var entity = await unitOfWork.Organization.AddAsync(organization); await unitOfWork.CompleteAsync(); fileService.Add(); return(EntityOperationResult <Organization> .Success(organization)); } catch (Exception ex) { return(EntityOperationResult <Organization> .Failure().AddError(ex.Message)); } } }
public async Task <EntityOperationResult <Basket> > CreateItemAsync(BasketCreateDto basketCreateDto) { using (var unitOfWork = _unitOfWorkFactory.MakeUnitOfWork()) { int countInverory = basketCreateDto.BasketInventoryDto.Sum(x => x.CountInventory); if (countInverory <= 0) { return(EntityOperationResult <Basket> .Failure() .AddError("Вы не указали количество товара")); } if (basketCreateDto.BasketInventoryDto.Any(x => x.CountInventory < 0)) { return(EntityOperationResult <Basket> .Failure() .AddError("Вы указали отрицательное число товара")); } try { var basket = new Basket { UserId = basketCreateDto.UserId, CountInventory = countInverory, OrganizationId = basketCreateDto.OrganizationId, Sum = basketCreateDto.BasketInventoryDto.Sum(x => x.Price * x.CountInventory), Status = false, DateAction = DateTime.Now }; var entity = await unitOfWork.Basket.AddAsync(basket); await unitOfWork.CompleteAsync(); var basketCheck = unitOfWork.Basket.GetById(entity.Id); if (basketCheck != null) { foreach (var rec in basketCreateDto.BasketInventoryDto.Where(x => x.CountInventory > 0)) { var basketInventory = new BasketInventory { BasketId = entity.Id, DishId = rec.DishId, CountInventory = rec.CountInventory, Price = rec.Price, Sum = rec.CountInventory * rec.Price }; var basketInventoryCheck = await unitOfWork.BasketInventory.AddAsync(basketInventory); await unitOfWork.CompleteAsync(); } } return(EntityOperationResult <Basket> .Success(entity)); } catch (Exception ex) { return(EntityOperationResult <Basket> .Failure().AddError(ex.Message)); } } }