LINQ to SQL ObjectDisposedException on entity that never asked for

落花浮王杯 提交于 2020-01-06 04:54:12

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!