简体   繁体   中英

LINQ to SQL “cannot access disposed object” exception

My code is throwing an exception when I attempt to access children of an object I retrieved from the database. I am using LINQ to SQL.

using (var DC = new MyDataContext())
{

    TimeSlot timeSlot = DC.TimeSlots
    .Where(w => w.FacilityID == facilityID
    .OrderByDescending(o => o.LoadDate)
    .FirstOrDefault();

    return timeSlot;

}

// Much later...
var slotChildren = timeSlot.children; // EXCEPTION!! Cannot access a disposed object.

The only way I have been able to make this work is by forcing the load with timeSlotForDay.LMSTimeSlotHours.Load() but that feels hacky. I have a hunch that one of the main issues is .FirstOrDefault() because I have tried many different things, even producing a nice join using projection using this code http://pastie.org/private/zzb01oeimkpelqz14gi7q that I got from this blog: https://eprystupa.wordpress.com/2009/11/26/linq-to-sql-tricks-building-efficient-queries-that-include-reference-data-or-child-entities/ , running the generated SQL in Microsoft SQL Server produces the expected results but after I return. But it seems like something is throwing away my data instead of loading it. My other alternatives would be to return the children in a seperate method entirely. This seems silly though because I have plenty of other methods in my project where I can grab one entity and then reach through to all the other children without these issues.

The problem is you're trying to access a property that isn't yet loaded, but after you've already disposed of your data context. In other words, you can't query the database after you've disposed of the connection to the database.

You have a couple solutions. Either keep the data context alive for longer, and continue to lazy load the children, or you can use LoadWith to force loading during the initial query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM