Exemple #1
0
        /// <summary>
        /// Adds the product to the wishlist of the specified user.
        /// </summary>
        /// <param name="userId">The id of the user to add to.</param>
        /// <param name="productId">The id of the product to add.</param>
        public async Task AddToWishlistAsync(int userId, int productId)
        {
            // Checks the product is not in the user's wishlist already:
            if (await _dbContext.UserWishlistProducts.AnyAsync(uwp => uwp.UserId == userId && uwp.ProductId == productId) == false)
            {
                // Adds to the database:
                UserWishlistProduct wishlistProduct = new UserWishlistProduct()
                {
                    UserId    = userId,
                    ProductId = productId
                };
                _dbContext.UserWishlistProducts.Add(wishlistProduct);
                await _dbContext.SaveChangesAsync();

                // Adds to the cache:
                wishlistProduct = await _dbContext.UserWishlistProducts
                                  .Include(uwp => uwp.Product).Include(uwp => uwp.Product.Sale)
                                  .FirstOrDefaultAsync(uwp => uwp.UserId == userId && uwp.ProductId == productId);

                User user = await this.GetByIdAsync(userId);

                user.Wishlist.Add(wishlistProduct);
                _userCache.Set(user);
            }
        }
Exemple #2
0
        /// <summary>
        /// Removes the product from the wishlist of the specified user.
        /// </summary>
        /// <param name="userId">The id of the user to remove from.</param>
        /// <param name="productId">The id of the product to remove.</param>
        public async Task RemoveFromWishlistAsync(int userId, int productId)
        {
            User user = await this.GetByIdAsync(userId);

            // Checks the product is in the user's wishlist:
            UserWishlistProduct wishlistProduct = user.Wishlist.FirstOrDefault(uwp => uwp.ProductId == productId);

            if (wishlistProduct != null)
            {
                // Updates the database:
                _dbContext.UserWishlistProducts.Remove(wishlistProduct);
                await _dbContext.SaveChangesAsync();

                // Updates the cache:
                user.Wishlist.Remove(wishlistProduct);
                _userCache.Set(user);
            }
        }