Context.detach - for garbage collection

My application uses one instance of the context that exists for the lifetime of the application. I am using Entity Framework to read and write all data to a database. After adding the objects, I want the garbage collectors to clear them so that they are not stored in memory. I tried the following:

    While context.BatchProgresses.Count > 0
        context.Detach(context.BatchProgresses.First())
    End While

but it runs through an endless cycle. Should I Context.Detach()remove items from Context.BatchProgresses?

+3
source share
2 answers

As usual in such cases, if you do not want to re-query the database, but work with entities related 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);
}

ObjectState EntityState.Detached . , attachEntities - .

+1

, BatchProgress.First() . , ( SQL) - SQL- .

(#)

var list = context.BatchProgress.ToList();
foreach(var item in list)
    context.Detach(item);
0

Source: https://habr.com/ru/post/1753780/


All Articles