views:

34

answers:

2

My application uses one context instance which exists for the life of the application. I am using Entity Framework to read and write all data to the database. After I add objects, I want them to be cleaned by the garbage collector so they don't persist in memory. I've tried:

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

but this is an infinite loop when run. What gives? Shouldn't Context.Detach remove items from Context.BatchProgresses?

A: 

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);
STO
Unfortunately context.BatchProgresses.ToList() will also cause a db query.
Yakimych
A: 

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.

Yakimych