At some point in the system some records are selected and must be replicated by changing only one value.
At this point I'm selecting the records that I need to insert:
listaRegistros = listaRegistros .GroupBy(r => r.Id)
.Select(grp => grp.First()).ToList();
I then use these records selected above to insert new records into the table:
foreach (var orgao in listaOrgaosASeremAdicionados)
{
foreach (var registro in listaRegistros)
registro.Orgao = orgao;
new RegistrosMeService().InsertListaRegistrosMe(listaRegistros);
}
Here is the InsertListaRegistrosMe
of class RegistrosMeService
:
protected EFSpecificRepository<TB_RegistrosMe, Entities> _repository;
protected EFSpecificRepository<TB_RegistrosMe, Entities> Repository
{
get
{
if (_repository == null)
_repository = new EFSpecificRepository<TB_RegistrosMe, Entities>();
return _repository;
}
}
public int InsertListaRegistrosMe(List<TB_RegistrosMe> listaMe)
{
Repository.InsertList(listaMe);
Repository.SaveChanges();
}
The first loop
, where the insertion is done, is to inform for how many organs the list of records will be added, more than one may have been selected.
The only change made to the registry is the one that can be checked in loop
, which is the change of registro.Orgao
.
The problem is that in Insert the error occurs:
"An object with the same key already exists in the ObjectStateManager. is in the Unchanged state. An object can only be added objectStateManager if it is in the added state. "
I have tried to change the Id, but when trying to do this also an error occurs:
The 'Id' property is part of the object's key information and does not can be modified.
So I understand this problem occurs because I am observing a record that already exists in EF and for security it does not allow me to add this record because it considers it to be duplicate, correct?
But how could I solve this without having to create a new object in EF 3.5 (v1)? Is it possible to change the ObjectStateManager
so that it allows me to insert?