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;
}
}
}
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.You're disposing the
DataContext
but returning something that still depends on it.Options:
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 requiredToList()
inside theGet()
method'susing
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: