What happens if I attach an object that is already attached in EF?

I store some EF entities

in a cache layer that I wrote. When I fetch them from the cache, I sometimes get the "contextObject isposed" error. I want to add a new one contextObject

after getting the entity from the cache. What side effects can this cause? What happens if I attach an object that is already attached? Performance?

+3


source to share


3 answers


try to do this.

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

      



check this answer also. Object bound to data context

+1


source


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 for getting all objects in the Context.

+1


source


It will throw an exception (not sure what) because the object is already attached.

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

By the way, you should get rid of your context object as soon as you finish using it. You will get some weird behavior if not (objects don't update, cached objects changed directly in db don't reflect changes, etc.).

Sincerely.

0


source







All Articles