I have the following model:
In the database, suppose I have the user Administrator and an artifact which is created and modified by this user Administrator.
The code bellow is not working, and I would like to know what exactly is happening and how could I make it work? Important: When the artifact is created/edited by different users, it works like a charm.
using (var context = new ModelEntities())
{
//Get an artifact created and edited by the user Administrator
var artifact = context.Artifact
.AsNoTracking()
.First(a => a.Name == "Artifact created/edited by the same user");
var createdUser = artifact.CreatedBy;
Console.WriteLine("{0} created.", createdUser.Name); // Administrator created.
var modifiedUser = artifact.ModifiedBy;
Console.WriteLine("{0} modified.", modifiedUser.Name); // Administrator modified.
context.Set<Artifact>().Attach(artifact); // **Exception! An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.**
artifact.Name = "New Name";
context.Entry(artifact).State = EntityState.Modified;
context.SaveChanges();
}
It seems to be a Entity Framework limitation to have two entities of same types in two different navigation properties.
Notice that I've tried to create this sample as simple as possible, removing obvious fields commonly required by business rules (like a datetime for creation and modification).