I can create an object, but I cannot edit it

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);     // 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
}

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 it 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 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
    }
}

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?

+3
source share
1 answer

Instead of this:

// We're updating an existing product, but it 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);     

to try:

Product origProduct =_entities.Products.Where(m=>m.ProductId == product.ProductId).Single();
_entities.Products.Attach(product, origProduct);

This is loaded into the original object, which is attached, and gives it new values. ProductId was a hunch .... This will be your key.

0
source

All Articles