Home > OS >  Remove product by id api/order/{id} EF C#
Remove product by id api/order/{id} EF C#

Time:10-12

I want to make a remove method from db by id. My problem is in productcontroller.cs, Got wrong argument when I type id in var product = await _productRepository.RemoveProductByIdAsync()

ProductController.cs

[HttpPut("{id}")]
        public async Task<IActionResult> RemoveProduct(long id)
        {
            var product = await _productRepository.RemoveProductByIdAsync();
            if ( product is null)
            {
                return NotFound();
            }

            
            product.Remove(RemoveProduct);
            return NoContent();


        }

ProductRespository.cs

 public async Task RemoveProductByIdAsync(Product product)
        {
            _context.Products.Remove(product);
            await _context.SaveChangesAsync();
        }

IProductRespository.cs

Task RemoveProductByIdAsync(Product product);

CodePudding user response:

This

await _productRepository.RemoveProductByIdAsync();

does require a product You get the id from the task

[HttpDelete("{id}")]
        public async Task<IActionResult> RemoveProduct(long id)

So first get your product, for instance like this:

var prod = await _productRepository.GetProductByIdAsync(id);

and then delete it; like so:

await _productRepository.RemoveProductByIdAsync(prod);

in total:

var prod = await _productRepository.GetProductByIdAsync(id);
if (prod != null)
{
     await _productRepository.RemoveProductByIdAsync(prod);
}

and don't throw a 404 - because you already intended to delete it anyway

  • Related