How do I detach objects in Entity Framework Code First?

Entity FrameworkEntity Framework-4.1Ef Code-First

Entity Framework Problem Overview


There is no Detach(object entity) on the DbContext.

Do I have the ability to detach objects on EF code first?

Entity Framework Solutions


Solution 1 - Entity Framework

This is an option:

dbContext.Entry(entity).State = EntityState.Detached;

Solution 2 - Entity Framework

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 3 - Entity Framework

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().

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShawn McleanView Question on Stackoverflow
Solution 1 - Entity FrameworkSlaumaView Answer on Stackoverflow
Solution 2 - Entity FrameworkLadislav MrnkaView Answer on Stackoverflow
Solution 3 - Entity FrameworkThe FabioView Answer on Stackoverflow