My application uses one 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With