コード例 #1
0
        public IActionResult Post([FromBody] Order order) //Cria um novo pedido
        {
            order.IsOrderCompleted = false;
            order.OrderPlaced      = DateTime.Now;
            _dbContext.Orders.Add(order);
            _dbContext.SaveChanges();

            var shoppingCartItems = _dbContext.ShoppingCartItems.Where(cart => cart.CustomerId == order.UserId);

            foreach (var item in shoppingCartItems)
            {
                var orderDetail = new OrderDetail()
                {
                    Price       = item.Price,
                    TotalAmount = item.TotalAmount,
                    Qty         = item.Qty,
                    ProductId   = item.ProductId,
                    OrderId     = order.Id,
                };
                _dbContext.OrderDetails.Add(orderDetail);
            }

            _dbContext.SaveChanges();
            _dbContext.ShoppingCartItems.RemoveRange(shoppingCartItems);
            _dbContext.SaveChanges();

            return(Ok(new { OrderId = order.Id }));
        }
コード例 #2
0
        public IActionResult Post([FromBody] Product product)     //Adiciona um novo produto
        {
            if (product == null)
            {
                return(BadRequest("Produto nulo"));
            }

            _dbContext.Products.Add(product);
            _dbContext.SaveChanges();
            return(StatusCode(StatusCodes.Status201Created));
        }
コード例 #3
0
        public IActionResult Post([FromBody] Restaurant restaurant)
        {
            var NameRestaurant = _dbContext.Restaurants.SingleOrDefault(u => u.Name == restaurant.Name);

            if (NameRestaurant != null)
            {
                return(StatusCode(StatusCodes.Status400BadRequest)); //Já possui restaurante com esse nome.
            }
            _dbContext.Restaurants.Add(restaurant);
            _dbContext.SaveChanges();
            return(StatusCode(StatusCodes.Status201Created));
        }
コード例 #4
0
        public IActionResult Post([FromBody] Category category)                                    //Adiciona uma categoria
        {
            var newCategory = _dbContext.Categories.SingleOrDefault(u => u.Name == category.Name); //Verifica se ja existe o mesmo email cadastrado no banco de dados

            if (newCategory != null)
            {
                return(StatusCode(StatusCodes.Status400BadRequest));
            }

            _dbContext.Categories.Add(category);
            _dbContext.SaveChanges();
            return(StatusCode(StatusCodes.Status201Created));
        }
コード例 #5
0
        public IActionResult Put(int id, [FromBody] User user)
        {
            var entity = _dbContext.Users.Find(id);

            if (entity == null)
            {
                return(NotFound("Usuário não enconrado !"));
            }
            entity.Name     = user.Name;
            entity.Email    = user.Email;
            entity.Password = SecurePasswordHasherHelper.Hash(user.Password);
            //Atualiza e salva o novo usuário ao banco de dados e retorna o StatusCode201Created.
            _dbContext.SaveChanges();
            return(Ok("Usuário atualizado com sucesso !"));
        }
コード例 #6
0
        public IActionResult Post([FromBody] ShoppingCartItem shoppingCartItem)
        {
            var shoppingCart = _dbContext.ShoppingCartItems.FirstOrDefault(s => s.ProductId == shoppingCartItem.ProductId && s.CustomerId == shoppingCartItem.CustomerId);

            if (shoppingCart != null)
            {
                shoppingCart.Qty        += shoppingCartItem.Qty;
                shoppingCart.TotalAmount = shoppingCart.Price * shoppingCart.Qty;
            }
            else
            {
                var sCart = new ShoppingCartItem()
                {
                    CustomerId  = shoppingCartItem.CustomerId,
                    ProductId   = shoppingCartItem.ProductId,
                    Price       = shoppingCartItem.Price,
                    Qty         = shoppingCartItem.Qty,
                    TotalAmount = shoppingCartItem.TotalAmount
                };
                _dbContext.ShoppingCartItems.Add(sCart);
            }
            _dbContext.SaveChanges();
            return(StatusCode(StatusCodes.Status201Created));
        }
コード例 #7
0
        public static void Initialize(DbContextOptions <DeliveryDbContext> options)
        {
            using (var context = new DeliveryDbContext(options))
            {
                context.Database.EnsureCreated();

                if (context.Restaurants.Any())
                {
                    return;
                }

                var restaurants = DataSource.Data
                                  .Select((r, i) =>
                {
                    r.Id = i + 1;
                    return(r);
                })
                                  .ToList();

                var tags = restaurants
                           .SelectMany(r => r.Tags)
                           .Distinct()
                           .Select((t, i) => new Tag {
                    Id = i + 1, Name = t
                })
                           .ToList();

                var restaurantTags = restaurants
                                     .SelectMany(r => r.Tags.Select(t => new RestaurantTag
                {
                    RestaurantId = r.Id,
                    TagId        = tags.Single(tag => tag.Name == t).Id
                }))
                                     .ToList();

                var dishes = restaurants.SelectMany(r => r.Dishes.Select(d => new Dish
                {
                    Name         = d.Name,
                    Description  = d.Description,
                    Price        = d.Price,
                    RestaurantId = r.Id
                }))
                             .Select((d, i) =>
                {
                    d.Id = i + 1;
                    return(d);
                })
                             .ToList();

                var random = new Random();
                var orders = restaurants
                             .SelectMany(restaurant =>
                {
                    var currentTime     = DateTime.Now;
                    var completedOrders = Enumerable
                                          .Repeat(0, random.Next(100))
                                          .Select(_ =>
                    {
                        var orderedAt = currentTime.AddDays(random.NextDouble() * -60);
                        return(new Order
                        {
                            Username = GetRandomUsername(),
                            OrderedAt = orderedAt.Truncate(),
                            CompletedAt = orderedAt.AddMinutes(random.NextDouble() * 30).Truncate(),
                            RestaurantId = restaurant.Id,
                        });
                    });

                    var pendingOrders = Enumerable
                                        .Repeat(0, random.Next(3))
                                        .Select(_ => new Order
                    {
                        Username     = GetRandomUsername(),
                        OrderedAt    = currentTime.AddMinutes(-random.Next(31)).Truncate(),
                        CompletedAt  = null,
                        RestaurantId = restaurant.Id,
                    });
                    return(completedOrders.Concat(pendingOrders));
                })
                             .Select((o, i) =>
                {
                    o.Id = i + 1;
                    return(o);
                })
                             .ToList();

                var ratings = orders
                              .Where(o => o.CompletedAt != null && random.Next(5) == 0)
                              .Select(o =>
                {
                    var currentTime = DateTime.Now;
                    return(new Rating
                    {
                        Username = GetRandomUsername(),
                        CreatedAt = o.CompletedAt.Value.AddHours(random.NextDouble() * 24).Truncate(),
                        Score = (byte)random.Next(6),
                        RestaurantId = o.RestaurantId,
                        OrderId = o.Id
                    });
                })
                              .Select((r, i) =>
                {
                    r.Id = i + 1;
                    return(r);
                })
                              .ToList();

                context.Restaurants.AddRange(restaurants.Select(ri => new Restaurant {
                    Id = ri.Id, Name = ri.Name, Distance = ri.Distance
                }));
                context.Tags.AddRange(tags);
                context.RestaurantTags.AddRange(restaurantTags);
                context.Dishes.AddRange(dishes);
                context.Orders.AddRange(orders);
                context.Ratings.AddRange(ratings);
                context.SaveChanges();
            }
        }