我想通過 id 從 db 中創建一個 remove 方法。我的問題是在productcontroller.cs,當我輸入了錯誤的引數id在var product = await _productRepository.RemoveProductByIdAsync()
產品控制器.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();
}
ProductRepository.cs
public async Task RemoveProductByIdAsync(Product product)
{
_context.Products.Remove(product);
await _context.SaveChangesAsync();
}
IProductRespository.cs
Task RemoveProductByIdAsync(Product product);
uj5u.com熱心網友回復:
這個
await _productRepository.RemoveProductByIdAsync();
確實需要產品您從任務中獲得 id
[HttpDelete("{id}")]
public async Task<IActionResult> RemoveProduct(long id)
所以首先得到你的產品,例如這樣:
var prod = await _productRepository.GetProductByIdAsync(id);
然后洗掉它;像這樣:
await _productRepository.RemoveProductByIdAsync(prod);
總共:
var prod = await _productRepository.GetProductByIdAsync(id);
if (prod != null)
{
await _productRepository.RemoveProductByIdAsync(prod);
}
并且不要拋出 404 - 因為無論如何你已經打算洗掉它
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/313310.html
下一篇:限制EF查詢以節省DTU
