How do I detach objects in Entity Framework Code First?
118,549
Solution 1
If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:
var data = context.MyEntities.AsNoTracking().Where(...).ToList();
As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.
Solution 2
This is an option:
dbContext.Entry(entity).State = EntityState.Detached;
Related videos on Youtube
Comments
-
Shawn Mclean over 2 years
There is no
Detach(object entity)
on theDbContext
.Do I have the ability to detach objects on EF code first?
-
Shawn Mclean about 13 yearsCan I do this when retrieving objects that returns an IQueryable?
-
Slauma about 13 years@Lol coder: I am not sure if I understand you right, but
entity
must be a materialized object of a type which is part of your model classes (Person, Customer, Order, etc.). You cannot directly pass in an IQueryable<T> intodbContext.Entry(...)
. Is that the question you meant? -
Slauma about 13 years@Ladislav: This is indeed probably what Lol coder meant. I've never used and thought about this method although I often load object lists and dispose the context at once, something like
using(ctx){ return ctx....ToList(); }
. In such cases usingAsNoTracking()
would make much sense because I'd save filling up the object context unnecessarily. I guess it would probably have a performance and memory consumption benefit especially for large lists, right? -
Ladislav Mrnka about 13 years@Slauma: Yes it has performance benefit. That is actually why this method exists. Using this approach in ObjectContext API is little bit more complicated.
-
Shawn Mclean about 13 yearsDoes this disable lazy loading?
-
Ladislav Mrnka about 13 yearsActually this will not disable lazy loading it will only disable change tracking and improve performance = entity is still attached. I found it after answering this question so you should mark @Slauma's one as a valid answer.
-
Shawn Mclean about 13 yearsThis is what I want. I want lazy loading and the ability to only modify a detached entity.
-
Slauma almost 13 years@Ladislav: To your comment above from Apr 16: Did you test this with a model with lazy loading enabled? I have just used
AsNoTracking
in a model without lazy loading and the entities are not attached to the context. Perhaps it is so: 1) Change tracking is always disabled (no snapshot is taken). 2) If lazy loading is disabled the entity is loaded in detached state, otherwise the entity is attached (necessary for lazy loading). -
Elad Benda about 11 yearswhat is the solution?
AsNoTracking()
orInclude()
ordbContext.Entry(entity).State = EntityState.Detached;
-
Slauma about 11 years@EladBenda: It depends. 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), useAsNoTracking
. -
kjbartel over 9 yearsI found an interesting problem with this method. Even though the entity may be a proxy class, lazy loading will not work after you change its state to
Detached
. -
Ricardo Souza almost 9 years@kjbartel : this is the expected behavior, since the entity has no link with the context.
-
kjbartel almost 9 years@rcdmk If you get an entity with
AsNoTracking
like in the other answer then lazy loading will still work. This method will not. -
Hamed over 3 yearsdon't forgot
SaveChange
andEntityState.Modified
beforeEntityState.Detached
-
Gert Arnold over 2 yearsboth would leave you with the entity still loaded into EF's Change Tracker -- That's not true. Detaching an object removes it from the change tracker. If the entity is a lazy-loading proxy then it has a reference to the context, but that's not the same as being attached to it (Ladislav's phrasing is a bit ambiguous here).
-
The Fabio over 2 yearsHi Gert, You can verify it with a quick test. The entity remains in the ChangeTracker with a state of detached. Similar to a memory leak (but unfortunately by design..). Calling the Clear command removes all of the instantiated entity objects from the Context
-
Gert Arnold over 2 yearsOf course the state is detached, what else? Even if you create a brand new entity that has never even seen a context its state is detached. It's just EF's way of saying: don't know this one, nothing to do with it. The alternative would be to throw an exception when verifying the state of any entity outside the context. Of course nobody wants that.
-
The Fabio over 2 yearsand yet EF retains it in memory detached like a memory leak
-
Gert Arnold over 2 yearsThen please show how. Your statement doesn't have any backing.
-
Gert Arnold over 2 yearsOnly lazy-loading proxies. And the context doesn't have reference to them when they're detached. It's not that EF keeps them in memory. It's the application that may keep proxies alive for a long time, which may cause a memory leak because the context they refer to can't be GC-ed. That's not EF's fault. Your statements are clearly rooted in the misconception that when EF reports an object as detached, it has to have it in its change tracker somehow. It hasn't.
-
The Fabio over 2 yearsYou are getting there, still have a little to learn from the usage of EF though. Good luck on your efforts
-
dalcam over 2 yearsThanks @TheFabio - this solved a massive performance issue when bulk inserting very large graphs in EF. To solve it, I used your line after saving each entity, and the performance increase and memory usage improvement was awesome. Thanks!