1
2
3
|
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。我下了断点检查了一下数据,是有值的。
2.我发现问题出在我访问了另一个实体的子实体,也就是一个表的字表数据,EF是ORM技术所以用面向对象的方式去访问这个子对象的属性。就报错了。
上网找了一下,看到老外这样说的
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.
提供了解决方案
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。