2
These are my example classes:
public class EntityA
{
public string Id { get; set; }
public decimal AproveValue { get; set; }
public string EntityB_Id { get; set; }
public virtual EntityB EntityBs { get; set; }
}
public class EntityB
{
public string Id { get; set; }
public decimal Name { get; set; }
}
This is my repository class:
public void Update(T entity)
{
_myDbSet.Attach(entity);
((IObjectContextAdapter)MyContext).ObjectContext.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
}
I use the Unit Of Work standard to manage context.
When I try to update the Entitya.Pass property and call the repository update method, in the _myDbSet.Attach(Entity) line this error is released:
Attaching an entity of type 'EntityB' 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.
I’ve tried it like this:
MyContext.Entry(model.EntityB).State = EntityState.Unchanged;
base.Update(model);
But it didn’t work!
I need to maintain navigable property.
And this problem happens with all navigable properties of the project.
Have you tried "Tasking" the entities? By your model, it seems to me that Entitya needs to be tied to Entityb, something like that:
MyContext.Attach(model.EntityB)
– Ricardo Pontual
Yes, I put it in the update before Atachar the entityA, but it gave the same error. I will try another solution if it works put here the result
– Ricardo Cardoso