public async Task <int> SaveAsync(BL.OrderLine entity) { try { if (entity == null) { return(0); } using (var context = _contextFactory.GetProductContext()) { var entityModel = await context .OrderLines .FirstOrDefaultAsync(item => item.Id.Equals(entity.Id)); if (entityModel == null) { entityModel = new DA.OrderLine(); MapForUpdateEntity(entity, entityModel); await context.OrderLines.AddAsync(entityModel); } else { MapForUpdateEntity(entity, entityModel); } context.SaveChanges(); return(entityModel.Id); } } catch (Exception ex) { throw ex; } }
private void MapForUpdateEntity(BL.OrderLine entity, DA.OrderLine daEntity) { daEntity.Id = entity.Id; daEntity.OrderId = entity.OrderId; daEntity.ProductId = entity.ProductId; daEntity.Price = entity.Price; daEntity.Quantity = entity.Quantity; }
public async Task <IActionResult> Post([FromBody] API.Order order) { try { var user = _userServ.GetUser(); if (user == null) { return(Unauthorized("User is not authentificated.")); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var cartLines = await _cartLineRepo.FindByAsync(c => c.UserId == user.Id); //if (cartLines.Count == 0) // return BadRequest("Cart is empty."); order.OrderTime = DateTime.Now; order.UserId = user.Id; order.Amount = cartLines.Sum(c => c.Price * c.Quantity); //маппировка, сохранение, получение ID новой записи var newOrderId = await _orderRepo.SaveAsync(_mapper.Map <BL.Order>(order)); foreach (var item in cartLines) { var orderLine = new BL.OrderLine { Quantity = item.Quantity, Price = item.Price, ProductId = item.ProductId, OrderId = newOrderId }; await _orderLineRepo.SaveAsync(orderLine); //сохранение новой записи строки заказа await _cartLineRepo.DeleteAsync(item.Id); //удаление строки корзины на основании которой создана строка заказа } return(Ok(order)); } catch (Exception ex) { return(BadRequest($"{ex.Message}")); } }