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?
I usually extend the base class(inherits from the DbContext) with the property:
later you can use this property for variety of useful stuff ... like Detach :)
EF:CF 4.1 RC1 and EF:CF 4.1 RTW have the same explicitly implemented IObjectContextAdapter:
Microsoft decided "Detach is too advanced technology and should be hidden". IMHO the man who invented this should be shot - because if you add brand new entity, it is otherwise difficult to just remove it without commiting changes to db (you can manipulate with DbEntityEntry but that's another story).
Edit 4 years later:
With EF6 (i somehow skipped EF5 :) ) you dont need
detach()
anymore, becouse removing freshly added entry does not generatedelete from [table] where [Id] = 0
as in EF4 - you can just callmySet.Remove(myFreshlyCreatedAndAddedEntity)
and everything will be allright.For people that might stumble upon this question, as of CTP5 you now need to write
in order to get to ObjectContext.
DbContext uses an ObjectContext internally and EF team make this available as a protected property just in case you ever need to drop down to the lower level API and sounds like this is the case here, so you can use or expose the required functionality from a derived DbContext:
Then you can call this method from your controller to detach an entity.
Alternatively, you can change it to even have a richer API:
Here is how DbContext looks like from metadata: