Beispiel #1
0
        public void UpdateSelection(int userId, int watchId, bool isChecked)
        {
            var shoppingCart = _context.ShoppingCarts.FirstOrDefault(_ => _.UserId == userId && _.WatchId == watchId);

            if (shoppingCart is null)
            {
                throw new Exception("Item not found");
            }

            shoppingCart.IsChecked = isChecked;
            _context.SaveChanges();
        }
Beispiel #2
0
        public void CreateOrder(OrderDTO orderDto, int userId)
        {
            var checkedItemsInCart = _context.ShoppingCarts
                                     .Where(_ => _.UserId == userId && _.IsChecked)
                                     .ToList();

            if (!checkedItemsInCart.Any())
            {
                throw new Exception(ERROR_MESSAGE);
            }

            var transaction = _context.Database.BeginTransaction();

            try
            {
                var orderEntity = _mapper.Map <Order>(orderDto);
                orderEntity.OrderDate  = DateTime.Now;
                orderEntity.UserId     = userId;
                orderEntity.TotalPrice = checkedItemsInCart.Sum(_ => _.Count * _.Watch.Price);
                orderEntity.TotalCount = checkedItemsInCart.Sum(_ => _.Count);

                var orderWatchLinks = _mapper.Map <IEnumerable <OrderWatchLink> >(checkedItemsInCart);

                foreach (OrderWatchLink item in orderWatchLinks)
                {
                    orderEntity.OrderWatchLinks.Add(item);
                }

                _context.Orders.Add(orderEntity);
                _context.OrderWatchLinks.AddRange(orderWatchLinks);
                _context.ShoppingCarts.RemoveRange(checkedItemsInCart);

                foreach (ShoppingCart item in checkedItemsInCart)
                {
                    item.Watch.CountInStock -= item.Count;
                }

                _context.SaveChanges();
                transaction.Commit();
            }
            catch
            {
                transaction.Rollback();
                throw;
            }
            finally
            {
                transaction.Dispose();
            }
        }