context.detach - for garbage collection
My application uses one开发者_JAVA技巧 context instance which exists for the lifetime of the application. I use Entity Framework to read and write all data to the database. After I add objects, I want them to be cleaned up by the garbage collector so that they don't persist in memory. I've tried the following:
While context.BatchProgresses.Count > 0
context.Detach(context.BatchProgresses.First())
End While
but this is runs into an infinite loop. Shouldn't Context.Detach()
remove items from Context.BatchProgresses
?
As usual in such cases, if you don't want to re-query the database, but work with entities attached to the context, you can use the ObjectStateManager:
var attachedEntities = context.
ObjectStateManager.
GetObjectStateEntries(EntityState.Added |
EntityState.Deleted |
EntityState.Modified |
EntityState.Unchanged).
Where(ent => ent.Entity is BatchProgress).
Select(ent => ent.Entity as BatchProgress).
ToList();
foreach (var attachedEntity in attachedEntities)
{
context.ObjectStateManager.ChangeObjectState(attachedEntity, EntityState.Detached);
}
Setting the ObjectState to EntityState.Detached removes the entity from the collection. You can check by fetching attachedEntities again in the end - there will be none.
It is only idea, but possible callingn of BatchProgress.First() causes database reading. Ensure (by logger or SQL profiler) no SQL activity is performed due that call.
Also you may try following code (C#)
var list = context.BatchProgress.ToList();
foreach(var item in list)
context.Detach(item);
精彩评论