public async Task <IActionResult> Put(int id, [FromBody] ProductModificationViewModel productVm) { if (productVm == null) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var dbItem = await _productRepository.GetSingleAsync(id); if (dbItem == null) { return(NotFound()); } Mapper.Map(productVm, dbItem); _productRepository.Update(dbItem); if (!await UnitOfWork.SaveAsync()) { return(StatusCode(500, "保存时出错")); } return(NoContent()); }
public IActionResult Put([FromBody] ProductModificationViewModel productModificationViewModel, int id) { if (productModificationViewModel == null) { return(BadRequest()); } if (productModificationViewModel.Name == "产品") { ModelState.AddModelError("Name", "名称不可以是产品"); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var model = _productRepository.GetProduct(id, false); if (model == null) { return(NotFound()); } //Mapper.Map<Product>(productModificationViewModel);//只是映射值,但并没有改变model的状态,所以持久化到数据库仍然没有变化 Mapper.Map(productModificationViewModel, model);//把第一个参数的值赋值到第二个参数上,并修改第二个参数的状态为modified,使之可以随DbContext持久化到DB if (!_productRepository.Save()) { return(StatusCode(500, "更新出错")); } //var model = ProductServicesMemory.productServices.products.Find(x => x.Id == id); //if (model == null) // return NotFound(); //model.Name = productModificationViewModel.Name; //model.Price = productModificationViewModel.Price; return(NoContent()); }