1
My problem is when I try to update an entity that has a child class that in turn has other children. The structure is this:
public class Diagrama
{
[Key]
public int Numero_Diagrama { get; set; }
public virtual List<Transicao> Transicoes { get; set; }
}
public class Transicao
{
[Key]
public int Numero_Transicao { get; set; }
public int Numero_Diagrama { get; set; }
public virtual List<Acao> Acoes { get; set; }
}
public class Acao
{
[Key]
public int Numero_Acao { get; set; }
public virtual List<Transicao> Transicoes { get; set; }
}
Diagram for Transition (1-n)
Transition to Actions (n-n)
modelBuilder.Entity<Transicao>()
.HasMany(s => s.Acoes)
.WithMany(c => c.Transicoes)
.Map(cs =>
{
cs.MapLeftKey("Numero_Transicao");
cs.MapRightKey("Numero_Acao");
cs.ToTable("wrfTransicaoAcoes");
});
When I try to change the diagram State to Modified it gives error:
System.Invalidoperationexception: 'Attaching an Entity of type 'Acao' 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.'
public virtual void Atualizar(TEntity obj)
{
ValidaEntidade(obj);
using (Contexto Db = new Contexto())
{
Db.Entry(obj).State = EntityState.Modified;
Db.SaveChanges();
}
}
This is happening because I have an Action in 2 different transitions. But I’m only changing the Diagram.
Data structure, already in the database and loaded in the Diagram class:
If I delete the last line of the 49 transition, everything works because it also references the 4 action.
Someone has a light?
What is the complete code of logic manipulating transitions and actions?
– Leonel Sanches da Silva
Hello @Ciganomorrisonmendez, actually the records already exist and are already linked correctly (I’m not saving the transition updating the diagram, I do it direct), the problem is when I try to update any property of the diagram.
– Marcelo Monteiro
Just to clarify, the relations between diagram x transitions x actions have already come from the bank ready. I am only changing the description of the diagram. I don’t know if that’s what I wanted to know
– Marcelo Monteiro
That one
obj
is aDiagrama
, right?– Leonel Sanches da Silva
That’s right. I asked the question a few more things, the data with are in the database.
– Marcelo Monteiro