Entity Framework: Object Refresh Error

0

I can not update my object. I created the method as follows:

public void Atualizar(T obj)
{
    banco.Entry(obj).State = EntityState.Modified;
    banco.SaveChanges();
}

The following exception was thrown:

Attaching an entity of type 'ProjetoTeste.Domain.Entities.Clientes.Cliente'
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.

em System.Data.Entity.Core.Objects.ObjectContext.VerifyRootForAdd(Boolean doAttach, String entitySetName, IEntityWrapper wrappedEntity, EntityEntry existingEntry, EntitySet& entitySet, Boolean& isNoOperation)
   em System.Data.Entity.Core.Objects.ObjectContext.AttachTo(String entitySetName, Object entity)
   em System.Data.Entity.Internal.Linq.InternalSet'1.c__DisplayClassa.b__9()
   em System.Data.Entity.Internal.Linq.InternalSet'1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
   em System.Data.Entity.Internal.Linq.InternalSet'1.Attach(Object entity)
   em System.Data.Entity.Internal.InternalEntityEntry.set_State(EntityState value)
   em System.Data.Entity.Infrastructure.DbEntityEntry'1.set_State(EntityState value)
   em ProjetoTeste.Infra.Data.Repositories.RepositoryBase'1.Atualizar(T obj) na D:\Informática\Raphael\Projetos VS2015\ProjetoTeste\Codigo\ProjetoTeste\ProjetoTeste.Data\Repositories\RepositoryBase.cs:linha 18

You're talking about the key conflict, I do not understand, since it's about update and not insert.

In the context I already added the client object, which I want to update:

public DbSet<Cliente> Clientes { get; set; }
    
asked by anonymous 15.07.2016 / 17:01

2 answers

1

Your update is not recognizing the object as an existing object. I've had the same problem other times, there are tips on that in another post.

a>

    
18.07.2016 / 20:11
0

You need to add obj to DbSet<T>

Example:

public void AtualizarCliente(Cliente obj)
{
      banco.Cliente.Add(obj);//Você adiciona o obj modificado no cliente
      Atualizar(obj);//Agora você pode mandar salvar.
}
    
17.03.2017 / 03:43