This seems to happen to me when I try to access a property that isn't one of the columns on the database table that the entity is derived from.
For example, maybe your database has a table Vehicle
with columns Id
, Year
, Make
, Model
, and EngineId
. The LinqToSql entity will have a property for each column, but it also adds a property called Engine
, which holds an Engine
entity.
If you convert your Vehicle
data to a List<Vehicle>
then try to access some property on the Engine
, you will get an ObjectDisposedException
unless your DataContext
is still active.
So, if you need, say, Vehicle.Engine.CylinderCount
after you're done with your DataContext
, you'll need to build a custom object that flattens your data so that you only need one "dot" to get to the data you need.
You can write a ViewModel
class to easily accomplish this. For example:
public class VehicleViewModel
{
public int Id { get; set; }
public int Year { get; set; }
public string Make { get; set; }
public string Model { get; set; }
public int EngineId { get; set; }
public int CylinderCount { get; set; }
}
Now, if you write your LinqToSql query to populate a List<VehicleViewModel>
instead of a List<Vehicle>
, you should stop getting an ObjectDisposedException
when you try to access the CylinderCount
.