There is no Detach(object entity)
on the DbContext
.
Do I have the ability to detach objects on EF code first?
This is an option:
dbContext.Entry(entity).State = EntityState.Detached;
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.
using(ctx){ return ctx....ToList(); }
. In such cases using AsNoTracking()
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?
Both previous answers provide good instructions, however, both might leave you with the entities still loaded into EF's context and/or its Change Tracker.
This is not a problem when you are changing small data sets, but it will become an issue when changing large ones. EF would have increased memory and resource usage, which in turn would reduce the procedure performance as it uses more data/entities.
Both other approaches are valid but, In this case, Microsoft recommends cleaning the Change tracker instead of detaching the entities individually
Clearing the Change tracker on the data changing loop (which changes a chunk of data for instance) can save you from this trouble.
context.ChangeTracker.Clear();
This would unload/detach all entities and its related changeTracker references from the context, so use with care after your context.SaveChanges()
.
Success story sharing
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?Detached
. If you want to load entities from the DB without attaching them at all to the context (no change tracking), useAsNoTracking
.AsNoTracking
like in the other answer then lazy loading will still work. This method will not.