public async Task <ActionResult <Combo> > CreateCombo([FromForm] ComboDto combo) { try { var cmbo = new Combo { Name = combo.Name, Description = combo.Description, Total = combo.Total }; await _unitOfWork.ComboRepository.InsertTask(cmbo); await _unitOfWork.Commit(); if (combo.Image != null) { var imageToRemove = await _unitOfWork.ComboImageRepository.GetByComboId(combo.Id); if (imageToRemove != null) { await _unitOfWork.ComboImageRepository.DeleteTask(imageToRemove.Id); } var comboImage = new ComboImage { ComboId = cmbo.Id }; using (var ms = new MemoryStream()) { combo.Image.CopyTo(ms); comboImage.Image = ms.ToArray(); } await _unitOfWork.ComboImageRepository.InsertTask(comboImage); await _unitOfWork.Commit(); } if (!string.IsNullOrEmpty(combo.ComboDetails)) { var comboDetailsJson = JsonConvert.DeserializeObject <List <ComboDetail> >(combo.ComboDetails);; var comboDetails = comboDetailsJson.Select(x => new ComboDetail { ComboId = cmbo.Id, DishId = x.DishId, Price = x.Price, Qty = x.Qty }).ToList(); await _unitOfWork.ComboDetailRepository.InsertRangeTask(comboDetails); await _unitOfWork.Commit(); } return(cmbo); } catch (Exception e) { return(BadRequest(e.Message)); } }
public async Task <IActionResult> UpdateCombo([FromForm] ComboDto combo) { try { var cmbo = new Combo { Id = combo.Id, Name = combo.Name, Description = combo.Description, Total = combo.Total }; _unitOfWork.ComboRepository.Update(cmbo); await _unitOfWork.Commit(); if (combo.Image != null) { var imageToRemove = await _unitOfWork.ComboImageRepository.GetByComboId(combo.Id); if (imageToRemove != null) { await _unitOfWork.ComboImageRepository.DeleteTask(imageToRemove.Id); } var comboImage = new ComboImage { ComboId = cmbo.Id }; using (var ms = new MemoryStream()) { combo.Image.CopyTo(ms); comboImage.Image = ms.ToArray(); } await _unitOfWork.ComboImageRepository.InsertTask(comboImage); await _unitOfWork.Commit(); } if (!string.IsNullOrEmpty(combo.ComboDetails)) { var comboDetailsJson = JsonConvert.DeserializeObject <List <ComboDetail> >(combo.ComboDetails);; var comboDetails = comboDetailsJson.Select(x => new ComboDetail { ComboId = cmbo.Id, DishId = x.DishId, Price = x.Price, Qty = x.Qty }).ToList(); await _unitOfWork.ComboDetailRepository.InsertRangeTask(comboDetails); await _unitOfWork.Commit(); var comboDetailsDb = await _unitOfWork.ComboDetailRepository.GetDetailsByComboNoTracking(combo.Id); var ids = comboDetails.Select(x => x.Id); if (comboDetailsDb.Count >= comboDetails.Count) { var removeDetail = comboDetailsDb.Where(p => !comboDetails.Any(p2 => p2.Id == p.Id)).ToList(); _unitOfWork.ComboDetailRepository.DeleteRange(removeDetail); await _unitOfWork.Commit(); } _unitOfWork.ComboDetailRepository.UpdateRange(comboDetails); } await _unitOfWork.Commit(); } catch (Exception e) { return(BadRequest(e.Message)); } return(Ok(combo)); }