An entity object cannot be referenced by multiple instances of IEntityChangeTracker

asp.net c# caching entity-framework

Question

I use EF as ORM.

I dispose the objectContext on every request.

I save the entities in a cache layer, as my service gets lots of traffic.

I got sometimes get the error objectContext already disposed for some entities that I got from the cache.

I have added this code to elements that were retrived from the cache

if (maMDBEntities.Entry(group).State == EntityState.Detached)
{
    maMDBEntities.Groups.Attach(group);
}

but now I sometimes get this error:

An entity object cannot be referenced by multiple instances of IEntityChangeTracker.

Was using Attach() an incorrect solution from the first place?

1
3
2/6/2013 9:48:36 AM

Accepted Answer

As we told you in your other question (will EF::attach(entity) will solve objectContext is already desposed?), you have to detach the Entities before attaching it to another Context!

If maMDBEntities is a new Context (not the one, which loaded the data), the EntityState is not "attached" from this Contexts point-of-view. So your check is not sufficient.

This maMDBEntities.Entry(group).State == EntityState.Detached will always be true for an Context, which did not load the Entity.

4
5/23/2017 11:45:52 AM


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