How can "An entity object cannot be referenced by multiple instances of IEntityChangeTracker" be resolved?

entity-framework

Question

I have a model in Ado.Net EF. I have a one to many relation and when I want to Add the entities I get the error

"An entity object cannot be referenceed by multiple instances of IEntityChangeTracker"

Any clue?

Something similar to

Template template = new Template();
...
...
while (from < to)
{
    Course course = new Course();
    .....
    template.Course.Add(course);
    .....
}
courseEntities.AddToTemplate(template); // Problem line
courseEntities.SaveChanges();
1
15
3/6/2009 7:38:42 PM

Accepted Answer

I was getting this message until i started to store the data context in the HttpContext.Items Property. This means you can use the same data context for the current web request. That way you don't end up with 2 data contexts referencing the same entities.

Here is a good post on DataContext Life Management.

I hope it helps.

Dave

17
3/6/2009 9:20:35 PM

Popular Answer

"template", or something that it references, has already been added to courseEntities or another context. I don't see anything in the code you show it would do that, but it is certainly happening. Perhaps it's happening in some of the code that you've trimmed. Look at the EntityState property of "template" in the debugger, and look at the EntityState of the properties of "template" as well. This should help you find out which entity instance is already in a context.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow