Good morning, people,
On my system here at work I have the following architecture: A PROJECT (which has some information) is composed of several PARTS. The parts are very different from each other. One, for example part 1, has several attached documents.
Projects view was assembled with a tab panel (one tab for each part) so that the user can change various parts at once.
In the Projects controller, I get the Project template from the view, with all its changes and inclusions. And start analyzing it:
private void salvar(Projetos projeto)
{
try
{
resolverParte1(projeto);
resolverParte2(projeto);
...
ctx.Entry(projeto).State = EntityState.Modified;
ctx.SaveChanges();
}
catch (Exception ex)
{
}
}
private void resolverParte1(Projetos projeto)
{
foreach(var d in projeto.Documentos.ToList())
{
// Documento alterado
if(d.id != 0)
{
ctx.Entry(d).State = EntityState.Modified;
}
else // Documento adicionado
{
d.Parte1Id = parte1Id;
ctx.Entry(d).State = EntityState.Added;
}
}
ctx.Projetos.Attach(projeto);
ICollection<Documentos> dLista = null;
ctx.Entry(projeto).Collection("Documentos").Load();
dLista = projeto.Documentos;
// A lista de documentos que permaneceu no banco como Unchanged é porque foi excluída na view
var apagados = (from d in dLista where ctx.Entry(d).State = EntityState.Unchanged select d).ToList();
foreach(var a in apagados)
{
ctx.Entry(a).State = EntityState.Deleted;
}
}
The problem I'm having is that when adding two or more documents (d1 and d2), they arrive at the controller with id = 0 (because I'm adding) and run the line attach occurs the following exception "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager can not track multiple objects with the same key" .
Please, would anyone know how to solve this?
Thank you very much.