Skip to main content
Commonmark migration
Fonte Link

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.

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.

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.

Várias coisas.
Fonte Link
Leonel Sanches da Silva
  • 89,6mil
  • 9
  • 125
  • 233

O controller foi gerado pelo scaffoldingscaffolding, ou seja, veio pronto, mas eu fiz algumas alterações devido ao fato de eu querer que os atributos de data (created e updated) sejam automáticos.

Quando ele chega no "EntityState.Modified, ele traz a seguinte mensagem de erro: "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."

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.

Estou analisando e entendi o seguinte: O erro só ocorre quando eu utilizo o find e trago o registro do BD. Mas pqpor que isso está acontecendo? Que diabo de entidade que já esta usando a mesma primary keyprimary key? Alguém sabepode me dar uma luz?

O controller foi gerado pelo scaffolding, ou seja, veio pronto, mas eu fiz algumas alterações devido ao fato de eu querer que os atributos de data (created e updated) sejam automáticos.

Quando ele chega no "EntityState.Modified, ele traz a seguinte mensagem de erro: "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."

Estou analisando e entendi o seguinte: O erro só ocorre quando eu utilizo o find e trago o registro do BD. Mas pq isso está acontecendo? Que diabo de entidade que já esta usando a mesma primary key? Alguém sabe me dar uma luz?

O controller foi gerado pelo scaffolding, ou seja, veio pronto, mas eu fiz algumas alterações devido ao fato de eu querer que os atributos de data (created e updated) sejam automáticos.

Quando ele chega no "EntityState.Modified, ele traz a seguinte mensagem de erro:

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.

Estou analisando e entendi o seguinte: O erro só ocorre quando eu utilizo o find e trago o registro do BD. Mas por que isso está acontecendo? Que diabo de entidade que já esta usando a mesma primary key? Alguém pode me dar uma luz?

Fonte Link

Entity Framework - Ao editar, falha no "db.Entry(category).State = EntityState.Modified;"

Possuo uma Entidade "Category", que contém id, nome, created e updated. Estou usando Code First.

Este é meu modelo:

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

O controller foi gerado pelo scaffolding, ou seja, veio pronto, mas eu fiz algumas alterações devido ao fato de eu querer que os atributos de data (created e updated) sejam automáticos.

No método create, vejam a alteração que eu fiz:

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

Este funciona bem. Quando crio uma nova categoria, ele atribui estes valores ao atributo e salva corretamente. O problema aparece no momento de editar.

Vejam as mudanças que fiz no controller gerado pelo próprio Entity Framework:

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

Quando ele chega no "EntityState.Modified, ele traz a seguinte mensagem de erro: "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."

Estou analisando e entendi o seguinte: O erro só ocorre quando eu utilizo o find e trago o registro do BD. Mas pq isso está acontecendo? Que diabo de entidade que já esta usando a mesma primary key? Alguém sabe me dar uma luz?