Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Code First - No Detach() method on DbContext

I'm wondering why there is no Detach method on the DbContext object like there is for ObjectContext.  I can only assume this omission was intentional, but I have a hard time figuring out why.  I need to be able to detach and re-attach entities (for putting in the cache in an ASP.NET project, for example).  However, since I can't detach an entity, when I try to attach an entity that was associated with a previous context, I get the "An entity object cannot be referenced by multiple instances of IEntityChangeTracker" exception.

What's the guidance here?  Am I missing something?

like image 230
Brian Sullivan Avatar asked Nov 12 '10 18:11

Brian Sullivan


People also ask

How do I detach in Entity Framework?

If you want to detach an object that is already attached to the context, set the state to Detached . If you want to load entities from the DB without attaching them at all to the context (no change tracking), use AsNoTracking . @kjbartel : this is the expected behavior, since the entity has no link with the context.

Which method is used to let the DbContext know an entity should be deleted?

DbContext. Remove Method (Microsoft.

How does DbContext work in Entity Framework?

As per Microsoft “A DbContext instance represents a session with the database and can be used to query and save instances of your entities. DbContext is a combination of the Unit Of Work and Repository patterns.” In simplified way we can say that DbContext is the bridge between Entity Framework and Database.


1 Answers

For people that might stumble upon this question, as of CTP5 you now need to write

((IObjectContextAdapter)context).ObjectContext 

in order to get to ObjectContext.

like image 56
Joakim Avatar answered Sep 29 '22 07:09

Joakim