EF6 has a memory leak in some specific situations. Please look at following code.
using (var connection = new SqlConnection(connectionString))
using (var transaction = connection.BeginTransaction())
// need to use a lot of small updates instead of one update, because the count of affected records is very big and MemoryOverflow exception can be thrown
for (int i = 0; i < 100; i++)
using (var context = new DbContext(connection, false))
// some updates and inserts
// there is a memory leak.
// all disposed context are stayed in the memory
// the cause of this behavior is attached event handler for the event StateChange on connection
If DbContext is created with external connection, then such context will not be disposed, because EntityConnection attached an event handler to the StateChange event in the external connection and this handler is not detached during disposing of DbContext.
Therefore GC cannot collect this instance of context.
I use following workaround for this situation.
private static void ContextDisposingWorkaround(DbContext context)
var connection = context.Database.Connection;
var objectContext = ((IObjectContextAdapter) saveContext).ObjectContext;
ReflectionHelper.RemoveEventHandlers(typeof (DbConnection), "StateChange", "_stateChangeEventHandler", connection,
Need to call above method before disposing of context.