Why do I need a ToList() to avoid disposed context errors?

后端 未结 4 832
面向向阳花
面向向阳花 2021-01-11 18:30

I\'m writing some code to access a database using EntityFrameWork. The code is:

public IEnumerable GetRows(int id)
{
    using (var context = new         


        
4条回答
  •  粉色の甜心
    2021-01-11 19:04

    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.

提交回复
热议问题