0
I own a "Category" Entity, which contains id, name, created and updated. I am using Code First.
This is my model:
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public DateTime Created { get; set; }
public DateTime Updated { get; set; }
public virtual ICollection<Item> Items { get; set; }
}
The controller was generated by scaffolding, ie came ready, but I made some changes due to the fact that I want the date attributes (created and updated) be automatic.
In the create method, look at the change I made:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "CategoryId,Name,Created,Updated")] Category category)
{
//Eu inseri este trecho
if(category.Created == null || category.Created == Convert.ToDateTime("01/01/0001 00:00:00"))
{
category.Created = DateTime.Now;
}
category.Updated = DateTime.Now;
//termina aqui
if (ModelState.IsValid)
{
db.Categories.Add(category);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
This works well. When creating a new category, it assigns these values to the attribute and saves correctly. The problem appears when editing.
See the changes I made to the controller generated by the Entity Framework itself:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "CategoryId,Name,Created,Updated")] Category category)
{
//Eu inseri este trecho
category.Created = db.Categories.Find(category.CategoryId).Created;
category.Updated = DateTime.Now;
//Termina aqui
if (ModelState.IsValid)
{
db.Entry(category).State = EntityState.Modified; // Da erro aqui
db.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
When it arrives at "Entitystate.Modified, it brings the following error message:
An Exception of type 'System.Invalidoperationexception' occurred in Entityframework.dll but was not handled in user code
Additional information: Attaching an Entity of type 'Entities.Model.Category' 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.
I am analyzing and understood the following: The error only occurs when I use find and bring the BD record. But why is this happening? What a hell of an entity that’s already using the same Primary key? Someone can give me a light?