Cannot access a disposed object

2019-08-26 17:06发布

Hi could you help me with this error?
Cannot access a disposed object. Object name: 'DataContext accessed after Dispose.'.

in my GUI

 private void InitializePage()
    {
        cbCategory.DataSource = stock.StockCategory.Get();

    }

in Datamodel

 public IEnumerable<StockCategory> Get()
    {
        using (leDataContext db = new leDataContext())
        {
            try
            {
                var r = from s in db.StockCategories
                        select s;
                return r;
            }
            catch (Exception ex)
            {
                Logger.Error(typeof(StockCategory), ex.ToString());
                throw;
            }

        }

    }

2条回答
霸刀☆藐视天下
2楼-- · 2019-08-26 17:33

Because of lazy-loading there, the query isn't really executed on the linq statement line. It is executed when you loop over it, or in this case - when you run ToList on it.

When it is executed it must be inside the data context... which is not the case here. You can either return a List from the Get method or insert the setting of the cbCategory.DataSource value into the using (leDataContext...) scope.

查看更多
女痞
3楼-- · 2019-08-26 17:35

You're disposing the DataContext but returning something that still depends on it.

Options:

  • Don't dispose the DataContext. I know this sounds weird, but guidance from the LINQ to SQL team (well, Matt Warren) has indicated that in most cases (i.e. if you're not doing anything out of the ordinary) disposal is not required
  • Call ToList() inside the Get() method's using block.

Note that using a query expression with just a degenerate query is reasonably pointless. (If this is within your own code, even the implicit Select(s => s) won't actually be useful.)

I would suggest changing your method to:

public IList<StockCategory> GetAllStockCategories()
{
    using (leDataContext db = new leDataContext())
    {
        return db.StockCategories.ToList();
    }
}
查看更多
登录 后发表回答