3

I save some EF entities in a cache layer I wrote. When I retrieve them from the cache I sometimes get a "contextObject is disposed" error. I want to attach a new contextObject after I get the entity from the cache. What side effects could this cause? What happens if I attach an entity which is already attached? Performance?

Brian
  • 5,069
  • 7
  • 37
  • 47
Elad Benda
  • 35,076
  • 87
  • 265
  • 471

3 Answers3

2

Exception "An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."

See the Context.DbSet.Local() method to get all objects in Context.

phil soady
  • 11,043
  • 5
  • 50
  • 95
1

try like this.

ObjectStateEntry entry;
    if(context.ObjectStateManager.TryGetObjectStateEntry(entity, out entry)) {
        return (entry.State != EntityState.Detached);
    }

check for this Answer also. Entity Attached to a data context

Community
  • 1
  • 1
Ravi Gadag
  • 15,735
  • 5
  • 57
  • 83
0

It will throw an Exception (not sure which), because the object is already attached.

Just try it in code, it's very simple to try. It happened to me.

BTW, you should dispose your contextobject as soon as you end using it. You'll get some weird behavior if don't (objects not updated, cached objects modified directly in db does not reflect changes, etc).

Regards.

fabrosell
  • 614
  • 1
  • 8
  • 19
  • How can I verify via code if an entity is attached already? `if (maMDBEntities.Entry(group).State == EntityState.Detached)` – Elad Benda Feb 05 '13 at 16:29
  • If you get some object from EF, you're already attaching it. If any reference is still pointing to the object, it's already attached. I would try a different approach, not just checking if object is attached... – fabrosell Feb 05 '13 at 18:31
  • 1) `you should dispose your contextobject as soon as you end using it` - I do. That's what causes my probelm as the entity is saved in the cache way after the objectContext has been desposed. – Elad Benda Feb 05 '13 at 21:10
  • 2) `If you get some object from EF, you're already attaching it` - I get it from the cache. That's why I want to re-attach it to some objectContext – Elad Benda Feb 05 '13 at 21:11
  • 3) `would try a different approach, not just checking if object is attached` - what do you suggest to my caching - disposed objectContext problem? – Elad Benda Feb 05 '13 at 21:12
  • You approach may be flawed (2) : what if a user modifies data directly in DB? You got the cached copy without the latest change, cache is invalid (then EF will throw an exception if detects it). I suggest you do not cache at all with EF (3). – fabrosell Feb 05 '13 at 22:13
  • I expect high voloum of traffic to my appcliation, that's why I have added cache an a poller on the DB. – Elad Benda Feb 06 '13 at 07:22
  • If I were you, I'll let EF to handle the extra traffic. I'm not sure if adding an extra layer will help with that. – fabrosell Feb 06 '13 at 16:08