Here is my controller code:
[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);
}
[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);
}
They both call the Save () function, defined here:
public class ProductsRepository
{
private readonly MyDBEntities _entities;
public ProductsRepository()
{
_entities = new MyDBEntities();
}
public void SaveProduct(Product product)
{
if (product.ProductID == 0)
_entities.Products.Context.AddObject("Products", product);
else if (product.EntityState == EntityState.Detached)
{
_entities.Products.Context.Attach(product);
_entities.Products.Context.Refresh(System.Data.Objects.RefreshMode.ClientWins, product);
}
_entities.Products.Context.SaveChanges();
}
}
When I call Create, it gets into AddObject () in the SaveProduct () function and saves the file correctly.
When I call Edit, it only gets _entities.Products.Context.SaveChanges () in the SaveProduct () function, and the product is not saved.
What am I doing wrong?
source
share