How to clean-up an Entity Framework object context?
Daniel's answer worked for me, however the EntityFramework API is different in version 6+. Here is a method I added to my custom repository container that will detach all entities from the DbContext's ChangeTracker:
/// <summary>
/// Detaches all of the DbEntityEntry objects that have been added to the ChangeTracker.
/// </summary>
public void DetachAll() {
foreach (DbEntityEntry dbEntityEntry in this.Context.ChangeTracker.Entries().ToArray()) {
if (dbEntityEntry.Entity != null) {
dbEntityEntry.State = EntityState.Detached;
}
}
}
It was just a trivial bug but I am going to leave the question here - maybe it helps others.
I had the following
var objectStateEntries = this.objectContext
.ObjectStateManager
.GetObjectStateEntries(EntityState.Added);
foreach (var objectStateEntry in objectStateEntries)
{
this.objectContext.Detach(objectStateEntry);
}
while I wanted the following
foreach (var objectStateEntry in objectStateEntries)
{
this.objectContext.Detach(objectStateEntry.Entity);
}
and couldn't see it.