Reputation: 4570
I am getting this a generic error:-
Additional information: Attaching an entity of type 'entity' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate
Its happening below on the line when the entity is trying to change its state.
public void InsertOrUpdate(T entity)
{
if (entity.Id == default(int))
{
entity.Created = DateTime.Now;
entity.LastEdit = DateTime.Now;
Context.Initial.Add(initial);
}
else
{
entity.LastEdit = DateTime.Now;
Context.Entry(entity).State = System.Data.Entity.EntityState.Modified;
}
}
However, I am getting it when I
Context.T.Attach(entity)
And when I dont change the state info or use attach, it doesnt update anything.
Here is my Controller code
[HttpPost]
[Authorize]
public ActionResult Create(NewViewModel viewModel)
{
if (ModelState.IsValid)
{
m_CTS.InsertOrUpdate(viewModel.entity);
m_CTS.Save();
// My big problem is that the Primary key that
// was generated doesnt come back from the view
// once edited, so I have created a property in
// the viewmodel to handle this
viewModel.ID = viewModel.entity.Id;
return RedirectToAction("Edit", new { id = viewModel.entity.Id });
}
else
{
return View("New", viewModel);
}
}
[HttpGet]
[Authorize]
public ViewResult Edit(int id)
{
// Getting this from the same context of when it was created
viewModel.entity = respoitory.Find(id);
return View(viewModel);
}
[HttpPost]
[Authorize]
public ActionResult Edit(NewViewModel viewModel)
{
// Could be the problem : As I said above the ID on the entity.id
// never comes back from the view (because I am using a viewmodel?)
// So I need to assign the ViewModel ID to the entity model id
// before I try and update it
viewModel.entity.Id = viewModel.ID;
m_CTS.InsertOrUpdate(viewModel.entity);
m_CTS.Save();
return RedirectToAction("Edit", new { id = viewModel.entity.Id });
}
Is there a reason why I am getting this error with the above code?
Thanks
Upvotes: 0
Views: 1356
Reputation: 3082
You have identified the problem within the comments of your code:
// My big problem is that the Primary key that
// was generated doesnt come back from the view
// once edited, so I have created a property in the viewmodel to handle this
To fix this, add @Html.HiddenFor(m => m.Id)
to your view. Now when you POST to the controller, your view model parameter will contain the Id field that you sent to the view in the first place.
Upvotes: 2