问题
I have this strange behavior. Im Loading some entities in a List<> and append to a grid. When double click the grid i take the row cast to the entity and append to a property.
I have changed some things in my database and code and now i get this exception while i never wanted to check something on this Entity Reference.
Any Ideas?
回答1:
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
.
来源:https://stackoverflow.com/questions/2936873/linq-to-sql-objectdisposedexception-on-entity-that-never-asked-for