The ObjectContext instance has been disposed and can no longer be used for operations that require a

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

How to solve the error The ObjectContext instance has been disposed and can no longer be used for operations that require a connection

 1.今天查询数据的出现对象已经被释放,而后字段属性为null。我下了断点检查了一下数据,是有值的。html

2.我发现问题出在我访问了另外一个实体的子实体,也就是一个表的字表数据,EF是ORM技术因此用面向对象的方式去访问这个子对象的属性。就报错了。ui

上网找了一下,看到老外这样说的this

Company should be lazy-loaded in your case. But your entity now in detached state (context which loaded KBrand entity now disposed. So, when you are trying to access Company property, Entity Framework tries to use disposed context to make query to server. That gives you exception.spa

提供了解决方案code

RSPDbContext c = new RSPDbContext();
KBrand co = item.Tag as KBrand;
c.KBrands.Attach(co);
// use co.Company

OR you need to use eager loading, to have Company already loaded. Something like this when you getting items:
RSPDbContext db = new RSPDbContext();
var brands = db.KBrands.Include(b => b.Company).ToList();
// assign brands to listbox

具体的缘由提及来有点麻烦。涉及到POCO。server

相关文章
相关标签/搜索