Home > Mobile >  Updating Product's Price Without Effecting Default Price in Database
Updating Product's Price Without Effecting Default Price in Database

Time:08-11

I created one simple E-Commerce website. If I give an example from Amazon, like you see if you choose 128 GB price will be higher than 64 GB. So I want it my project too. I created some features for Laptop like RAM, SSD etc. When someone clicked 512 GB SSD (default is 256 GB) in the shopping cart price will be 100 dollar higher.

enter image description here

But when I choose the any upgrade, default price effecting too. In the database price changing and when I build program again price higher.

This is my code:

    public RedirectToActionResult AddToShoppingCart(int productId, decimal equipmentPrice)
    {
        var selectedProduct = _productRepository.GetProductById(productId);


        if (selectedProduct != null)
        {
            selectedProduct.Price  = equipmentPrice;
            _shoppingCart.AddToCart(selectedProduct);
        }

        return RedirectToAction("Index");
    }

CodePudding user response:

You have to clone the default object and then modify the price of the cloned-obj. Your code should be like:

if (selectedProduct != null)
{
    var clone = new Product()
    {
        Price = selectedProduct.Price,
        ...
    };
    clone.Price  = equipmentPrice
    _shoppingCart.AddToCart(clone);
}

That's beacuse selectedProduct points to the default object, and so you're editing also the obj. contained in the database

  • Related