关于处置 DataContext 和 DataBind()
因此,如果我有某种方法返回产品列表:
public IEnumerable<Product> List()
{
try
{
using (MyDataContext db = new MyDataContext ())
{
return db.Products.ToList();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
当我设置一个 Repeater
来将其作为数据源时:
protected void LoadList()
{
BusProducts products = new BusProducts();
rptProducts.DataSource = products.List();
rptProducts.DataBind();
}
我在 DataBind()< 上收到错误/code> 说我无法访问已处置对象 (MyDataContext)..
这是正确的吗?即使我用 .ToList()
返回所有内容?
So, if I have some method to return a list of products:
public IEnumerable<Product> List()
{
try
{
using (MyDataContext db = new MyDataContext ())
{
return db.Products.ToList();
}
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
When I set, let's say, a Repeater
to have this as it's datasource:
protected void LoadList()
{
BusProducts products = new BusProducts();
rptProducts.DataSource = products.List();
rptProducts.DataBind();
}
I get an error on the DataBind()
saying that I can't access the Disposed Object (MyDataContext)..
Is this right? Even if I'm returning all with .ToList()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您由于绑定而引用任何 Product 实体的导航属性(相关的父实体或子实体),那么即使使用 ToList,您也会遇到该异常。这是因为访问导航属性将需要在访问属性时对数据库进行额外的查询。如果 DataContext 已被释放,那么这将不起作用。
您可以通过在检索产品数据时立即加载相关数据来避免这种情况。这是通过预取机制 - DataContext.LoadOptions 使用 LoadWith 选项来完成的。
http://msdn.microsoft.com/en -us/library/Bb882681%28v=VS.90%29.aspx
If you are referencing any of the Product entities' navigation properties (related parent or child entities) as a result of the binding, then yes you will get that exception even with the ToList. This is because accessing the navigation properties will require additional queries to the database at the time the property is accessed. That won't work if the DataContext has been disposed.
You can avoid this by having the related data eagerly loaded when the product data is retrieved. This is accomplished with the prefetching mechanism - DataContext.LoadOptions, using the LoadWith option.
http://msdn.microsoft.com/en-us/library/Bb882681%28v=VS.90%29.aspx