这是我的 Controller 代码:
[HttpPost]
public ActionResult Edit(ProductViewModel viewModel)
{
Product product = _ProductsRepository.GetProduct(viewModel.ProductId);
TryUpdateModel(product);
if (ModelState.IsValid)
{
_productsRepository.SaveProduct(product);
TempData["message"] = product.Name + " has been saved.";
return RedirectToAction("Index");
}
return View(viewModel); // validation error, so redisplay same view
}
[HttpPost]
public ActionResult Create(CommodityCategoryViewModel viewModel)
{
Product product = new Product();
TryUpdateModel(product);
if (ModelState.IsValid)
{
_productsRepository.SaveProduct(product);
TempData["message"] = product.Name + " has been saved.";
return RedirectToAction("Index");
}
return View(viewModel); // validation error, so redisplay same view
}
它们都调用 Save() 函数,定义如下:
public class ProductsRepository
{
private readonly MyDBEntities _entities;
public ProductsRepository()
{
_entities = new MyDBEntities();
}
public void SaveProduct(Product product)
{
// If it's a new product, just attach it to the DataContext
if (product.ProductID == 0)
_entities.Products.Context.AddObject("Products", product);
else if (product.EntityState == EntityState.Detached)
{
// We're updating an existing product, but it's not attached to this data context, so attach it and detect the changes
_entities.Products.Context.Attach(product);
_entities.Products.Context.Refresh(System.Data.Objects.RefreshMode.ClientWins, product);
}
_entities.Products.Context.SaveChanges(); // Edit function hits here
}
}
当我调用 Create 时,它会命中 SaveProduct() 函数中的 AddObject(),并正确保存产品。
当我调用 Edit 时,它只会命中 SaveProduct() 函数中的 _entities.Products.Context.SaveChanges(),并且不会保存产品。
我做错了什么?
最佳答案
取而代之的是:
// We're updating an existing product, but it's not attached to this data context, so attach it and detect the changes
_entities.Products.Context.Attach(product);
_entities.Products.Context.Refresh(System.Data.Objects.RefreshMode.ClientWins, product);
尝试:
Product origProduct =_entities.Products.Where(m=>m.ProductId == product.ProductId).Single();
_entities.Products.Attach(product, origProduct);
这将加载附加的原始对象并为其赋予新值。 ProductId 是一个猜测....无论您的 key 是什么。
关于c# - 我可以创建实体,但无法编辑实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6181860/