1
votes

I am getting the following message when I try to update an entity, which have a collection asociated to it.

"An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."

I receive the entity with the new properties by parameter. Eventos has a collection of Clientes, whis comes with Eventos.

This is the code:

public int Modificar(Eventos eventos)
{
    try
    {
         DBEntities DB = new DBEntities();
         Eventos objEvento = 
             DB.Eventos.Where(x => x.Id_evento == eventos.Id_evento)
                       .SingleOrDefault();

         eventos.Porcentaje_Pagado = objEvento.Porcentaje_Pagado;

         DB.Eventos.Attach(eventos);
         DB.Eventos.ApplyCurrentValues(eventos);

         DB.ObjectStateManager
             .ChangeObjectState(eventos, System.Data.EntityState.Modified);
         DB.SaveChanges();
         return eventos.Id_evento;
    }
    catch (Exception )
    {
         throw;
    }

}

The problem is in the "attach".

What is the problem?

* EDIT **

It worked partially, it saved the new data for "Eventos", but I get the following error when I try to update the list of "Clientes" asociated to Eventos.

"The property 'Clientes' on type 'Eventos_...' cannot be set because the collection is >already set to an EntityCollection."

The error is in line: objEvento.Clientes = eventos.Clientes;

The code:

DBEntities DB = new DBEntities(); 
Eventos objEvento = DB.Eventos.Where(x => x.Id_evento == eventos.Id_evento).SingleOrDefault(); 
objEvento.Porcentaje_Pagado = eventos.Porcentaje_Pagado; 
objEvento.Clientes = eventos.Clientes; 
DB.SaveChanges();
2

2 Answers

0
votes

You've already loaded the entity with the following code:

 Eventos objEvento = 
         DB.Eventos.Where(x => x.Id_evento == eventos.Id_evento)
                   .SingleOrDefault();

You are going to need to update the entity which you have loaded into the object context.

Update objEvento and then apply and save.

0
votes

Try this instead:

public int Modificar(Eventos eventos) 
{ 
     DBEntities DB = new DBEntities(); 
     Eventos objEvento =  
         DB.Eventos.Where(x => x.Id_evento == eventos.Id_evento) 
                   .SingleOrDefault(); 


     objEvento.Porcentaje_Pagado =  eventos.Porcentaje_Pagado;

     DB.SaveChanges(); 

     return objEvento.Id_evento; 

}