简体   繁体   English

数据上下文和处置问题

[英]problems with data contexts and disposing

I have some C# code that looks like 我有一些看起来像的C#代码

using (DataContext db = new DataContext(Program.config.dbContextStr)) {
    Foo.bar(db);
}

So bar is a static method of class Foo, and bar uses the db object passed in. It also passes db object to some other methods that it calls. 因此,bar是Foo类的静态方法,而bar使用传入的db对象。它还将db对象传递给它调用的其他方法。

The problem is that I'm getting this exception: 问题是我收到此异常:

System.ObjectDisposedException: Cannot access a disposed object. 
Object name: 'DataContext accessed after Dispose.'.

I've looked around for solutions and people have suggested to forget the using declaration and to simply write: 我到处寻找解决方案,人们建议不要using声明,而只写:

DataContext db = new DataContext(blah);
Foo.bar(db); 
// Let the garbage collector go about its merry business.

and to disable deferred loading: 并禁用延迟加载:

db.DeferredLoadingEnabled = false;
Foo.bar(db);

I've tried both of these solutions, but I still get the exception. 我已经尝试了这两种解决方案,但仍然有例外。 Are there other things I should try? 还有其他我应该尝试的东西吗?

You are disposing the data context. 您正在处理数据上下文。

Firstly, the way you are using the data context is correct, wrapping it in a using . 首先,您使用数据上下文的方式是正确的,将其包装在using

This means that somewhere inside Foo.bar , you are disposing your data context; 这意味着在Foo.bar内部的某个Foo.bar ,您正在Foo.bar数据上下文; there is no other alternative. 没有其他选择。

This means you have to search your code for either one of the following constructs: 这意味着您必须在代码中搜索以下任一结构:

  • db.Dispose(); or 要么

  • using (db) { ... } . using (db) { ... }

Try to do a "Find all" in Visual Studio on the word "Dispose" or "using" and manually check all instances. 尝试在Visual Studio中对单词“ Dispose”或“ using”执行“全部查找”,然后手动检查所有实例。

我怀疑您正在将DataContext放置在Foo.bar(db);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM