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