实体框架和Web API的ObjectDisposedException [英] Entity Framework and Web API ObjectDisposedException
问题描述
我有一个使用实体框架5连接到SQL Server数据层。我也有一个LINQ查询,获取一些数据。使用Web API一起使用时,查询失败。我得到的ObjectDisposedException。这里的查询:
使用(MyContext集装箱=新myContext())
{
返回container.Sales
.INCLUDE(产品)
。凡(S => s.Id == id)的
.FirstOrDefault();
}
数据层是一个DLL,由一个业务层,还一个DLL,它是由一个网络API控制器称为露出。我曾假定JSON序列是懒加载包括但没有我的修复工作过。有任何想法吗?我会更新了一个问题,需要的话,如果信息丢失。
下面是业务层调用数据层:
公开发售GetSale(INT ID)
{
SaleRepository S =新SaleRepository();
返回s.GetSale(ID);
}
和最终的网络API调用业务层:
公开发售GetSale(INT ID)
{
SaleManager S =新SaleManager();
返回s.GetSale(ID);
}
下面是个例外:
的ObjectContext的实例已设置,不能再被用于需要连接的操作。
块引用>解决方案这是因为后正在执行延迟加载你的
的DbContext
已被释放。要解决这个问题,你可以这样做禁用延迟加载:
container.Configuration.LazyLoadingEnabled = FALSE;
I have a data layer that uses Entity Framework 5 to connects to Sql Server. I also have a LINQ query that gets some data. This query fails when used with Web API. I get the ObjectDisposedException. Here's the query:
using (MyContext container = new myContext()) { return container.Sales .Include("Products") .Where(s => s.Id == id) .FirstOrDefault(); }
The data layer is a dll, exposed by a business layer, also a dll, which is called by a web api controller. I had assumed that the JSON serializer was lazy loading the includes but none of my fixes have worked. Any ideas? I will update the question as need be if info is missing.
Here is the business layer call to the data layer:
public Sale GetSale(int id) { SaleRepository s = new SaleRepository(); return s.GetSale(id); }
And finally the web api call to the business layer:
public Sale GetSale(int id) { SaleManager s = new SaleManager(); return s.GetSale(id); }
Here is the exception:
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
解决方案This happens because lazy loading is being performed after your
DbContext
has been disposed.To resolve the issue you can disable lazy loading by doing this:
container.Configuration.LazyLoadingEnabled = false;
这篇关于实体框架和Web API的ObjectDisposedException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!