Entity Framework - When editing, "db. Entry(Category) fails. State = Entitystate.Modified;"

Asked

Viewed 598 times

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?

2 answers

3

Don’t take this the wrong way, but the solution to this is awful.

The mistake happens because of this:

    //Eu inseri este trecho  
    category.Created = db.Categories.Find(category.CategoryId).Created;
    category.Updated = DateTime.Now;
    //Termina aqui

First you selected the bank category, then asked the context to look at the same category that came from the screen:

db.Entry(category).State = EntityState.Modified; // Da erro aqui

It will even give error. Context can observe an object with the same primary key at a time. Select by .AsNoTracking() makes the code come easily in bad practices.

This field filling is not done this way. I teach you how to do it here.

0

I solved an identical problem using the solution below:

category.Created = db.Categories.AsNoTracking().Where(x => x.CategoryId == category.CategoryId).FirstOrDefault();

With Asnotracking(), entities will be read from the source of their data, but not kept in context.

I hope this helps!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.