且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

System.ObjectDisposedException:无法访问已处置的对象。对象名称:'Dispose后访问的DataContext。'。

更新时间:2023-02-17 20:08:05

你能用'批处理'来解释你的意思吗?或者"分批运行"而不是通过"另一个.Net程序"运行它?



唯一一次在您的代码调用Dispose方法之后,DataContext将被释放。如果您使用C#中的'using'语句之类的构造,则可能会发生这种情况。如果您正在处理DataContext并从方法中返回查询,则在执行查询时您将收到此消息,因为DataContext已被释放。您不需要Dipose DataContext。 Dispose方法适用于某些特定场景,例如需要在应用程序状态下保留实体的副本。如果要强制DataContext为Dispose,则必须在从方法返回之前执行查询。您可以通过在查询上调用ToList()来完成此操作。





Hello,

 

I have an executable process using a LINQ data context (LINQ to SQL).  For some reason, whenever I execute the process in another batch process, I'm getting the error in the subject line.  This occurs to the call DataContext.GetTable<TENtity>().

 

Has anybody else experienced this?  Again, the process works when I run it directly, and when I run it in batch, but when I try to run it through another .NET program, it fails.

 

Thanks.

Can you explain what you mean by 'batch process' or 'run it in a batch' versus running it through 'another .Net program'?

 

The only time a DataContext becomes disposed is after your code calls the Dispose method on it. This can happen on your behalf if your using a construct like the 'using' statement in C#.  If you are disposing the DataContext and returning a query out of a method, upon execution of the query you'll get this message because the DataContext is disposed.  You don't need to Dipose the DataContext. The Dispose method is there for some specific scenarios like needing to leave a copy of an entity in application state.  If you want to force the DataContext to Dispose, you'll have to execute the query before you return it from the method.  You can do this by calling ToList() on the query.