Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

context.detach - for garbage collection

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?

like image 891
Terry Avatar asked May 29 '26 03:05

Terry


1 Answers

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.

like image 96
Yakimych Avatar answered May 30 '26 16:05

Yakimych



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!