Question : Entity Framework - Inserting row into a table which as a self referencing

I have a table like this. I'm trying to insert NEW role using entity framework.

tblEmployee
- EmployeeId
- SupervisorId (Reference to EmployeeId)
- ...

//Code
var context = new Entities();
context.AddTotblEmployee(employeeObj);
context.SaveChanges();

When I use above code, it works fine when Supervisor is null. But when I attach the supervisor object, it fail. It said "An entity object cannot be referenced by multiple instances of IEntityChangeTracker."

Thank you for your comment.

Answer : Entity Framework - Inserting row into a table which as a self referencing

Hi winmyan;

Just learning ADO .Net Entity Framework and did a little research and found this which seems to be your issue.

Posted by Jeff Derstadt - MSFT
Currently ObjectContext does not detach objects that are being tracked when the context is disposed. This was an explicit design decision to avoid a performance hit when disposing a context with the intent to stop using both the context and all of the entities. However, when the lifetime of an entity is longer than a particular context, this can be an issue as you have seen. We have an active work item to do a better job of handling these cases so that an entity graph can be reattached to a context if it's old context has been disposed. In the mean time, you can also explicitly set the change tracker to 'null' for all the entities in your graph by using the methods on the IEntityWithChangeTracker interface (each entity type that participates in change tracking implements this interface). This will allow your entities to be reattached to another context without destroying the relationships between entities which is what will happen if you explicitly call "Detach" on all entities in the ObjectStateManager.

Original post at: http://social.msdn.microsoft.com/forums/en-US/adodotnetentityframework/thread/5ee5db93-f8f3-44ef-8615-5002949bea71/

From the above statement, "However, when the lifetime of an entity is longer than a particular context, this can be an issue as you have seen.", this would also be true if the original context has not been disposed of yet as well.

Fernando
Random Solutions  
 
programming4us programming4us