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?
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
maMDBEntitiesis 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.Detachedwill always be true for an Context, which did not load the Entity.