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;
}
}
}
You’re disposing the
DataContextbut 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’susingblock.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: