I am trying to modify model coming from View and then update my database using that model. My code can be seen below:
public ActionResult Edit(Saving saving)
{
if (ModelState.IsValid)
{
Int32[] ids = saving.CatIds.Split(',').Select(n => Convert.ToInt32(n)).ToArray();
foreach (var category in db.Category.Where(m => ids.Contains(m.id)).ToList())
saving.Category.Add(category);
db.ObjectStateManager.ChangeObjectState(saving, EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(saving);
}
my code gives this error:
The object cannot be attached because it is already in the object context. An object can only be reattached when it is in an unchanged state.
and if I try this code:
public ActionResult Edit(Saving saving)
{
if (ModelState.IsValid)
{
Int32[] ids = saving.CatIds.Split(',').Select(n => Convert.ToInt32(n)).ToArray();
foreach (var category in db.Category.Where(m => ids.Contains(m.id)).ToList())
saving.Category.Add(category);
db.ObjectStateManager.ChangeObjectState(saving, EntityState.Unchanged);
db.Saving.Attach(saving);
db.ObjectStateManager.ChangeObjectState(saving, EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(saving);
}
I am getting the error below:
Violation of PRIMARY KEY constraint ‘PK_ProductCategory_1’. Cannot insert duplicate key in object ‘dbo.ProductCategory’.
I dont know what to do and how to solve it. Any help will be appreciated. Thank You
Have you tried to just Attach it and then modify the properties?