2
Good morning Personal,
In 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.
The Projects view has been assembled with a Tab Panel (a tab for each part) so that the user can change several parts at once.
In the Project controller, I get the Project model from the view, with all its changes and inclusions. And I start to analyze 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 by adding two or more documents (D1 and D2), they arrive at the controller with id = 0 (because I’m adding) and when running the attach line, the following Exception occurs "An Object with the same key already exists in the Objectstatemanager. The Objectstatemanager cannot track Multiple Objects with the same key".
Please, someone would know how to fix this?
Thank you very much.