English 中文(简体)
不得接触被处置物体
原标题:Cannot access a disposed object

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

页: 1

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

    }

缩略语

 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;
            }

        }

    }
最佳回答

您重新编辑<代码>DataContext,但退回仍然取决于该编码的内容。

备选办法:

  • 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.

请注意,仅用先质质的质询来表示疑问,是不合理的。 (如果这属于你自己的法典,那么即使隐含的<代码>Select(s => s)实际上也是有益的。)

我建议改变你的方法,以便:

public IList<StockCategory> GetAllStockCategories()
{
    using (leDataContext db = new leDataContext())
    {
        return db.StockCategories.ToList();
    }
}
问题回答

由于电荷载到这里,在林克声明线上确实没有执行过盘问。 当你接手时,或者在此时,当你对List说话时,就处决了。

如果执行,则必须在数据范围内......这里的情况并非如此。 你们要么从Get方法中返回名单,要么加入造物。 数据输入<代码>使用(leDataContext...)的范围。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签