ObjectDisposedException EntityFramework

I had a using clause around my call to Entity Framework like so:

using (var ctx = new SubstationLoadContext())
{
IRepository repo =
new Repository(ctx);

AreaSummations = repo.GetAreaSummationsWithEquipmentWithReadingUnits();
}

Subsequently while performing a LINQ query on AreaSummations I received the fiendish ObjectDisposedException. Porquoi ?

Some quick Googling told me that since my context variable was being disposed before I performed the query I should force the creation of an in-memory List in order to detach from the database i.e. I should do a .ToList() like so:

AreaSummations = repo.GetAreaSummationsWithEquipmentWithReadingUnits.ToList();

But my repo method was already doing a .ToList(). I was already detached from the database wasn’t I? Nyet.

The Botswanian Programming Legend masquerading as Mark Gravell on Stack Overflow informed me that the issue was that EF was lazily-loading some portion of the object graph and I needed to force an eager load by use of Entity Framework .Include. HUZZAH!

But I was already forcing an eager load wasn’t I ? See…

summations = (from s in ((SubstationLoadContext)repo.Context)
.SubstationGroupSummationTypes
.Include("Equipments.EquipmentReadingUnits")

Mais Non! I was NOT forcing an eager load because I had improperly specified the path to EquipmentReadingUnits. I had only included the path from about half-way up the object graph I needed to include the full path from the root Entity. Like so:
summations = (from s in ((SubstationLoadContext)repo.Context)
.SubstationGroupSummationTypes
.Include("SubstationGroup.Substations.Equipments.EquipmentReadingUnits")

PROPER HUZZAH! The eager load was correctly specified and ObjectDisposedException was banished!

Moral of the Story:

When getting ObjectDisposedException with Entity Framework make sure you have correctly specified the path for your eager loads. And include them if they are not already present. And then you will no longer see this

System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection

Tags: , ,

Leave a comment