且构网

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

为什么我需要一个ToList()来避免出现上下文错误?

更新时间:2023-02-25 20:10:26

您需要调用 ToList ToArray 或其他枚举方法的原因EF返回的数据是LINQ中的查询执行被延迟:直到你明确看待数据才会被处理。当您的方法返回已经获取查询数据的上下文关闭时(您的使用块快速处理),导致您看到的异常。

The reason you need to call ToList, ToArray, or some other method that enumerates the data returned by EF is that query execution in LINQ is deferred: the data is not processed until you take it explicitly. By the time your method returns the context through which the query data has been obtained is closed (your using block takes care of that happening quickly), causing the exception that you see.

这样做是为了使代码不花时间处理你不需要的数据。例如,您可以编写开始读取客户端数据的代码,并在中间停止。如果查询执行没有推迟,您将花费时间和内存来获取查询的尾才能将其抛弃。延期执行让您处于控制之中:您可以根据您计划对数据做什么来决定要保留的数据,或将整个集合带入内存。

This is done so that the code is not spending time processing the data that you do not need. For example, you could write code that starts reading through the data on the client side, and stops in the middle. If query execution were not deferred, you would have spent time and memory obtaining the "tail" of the query only to throw it away. Deferred execution puts you in control: you decide what data you want to keep as you go, or bring the entire collection to memory based on what you plan to do with the data.