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

后端 未结 4 807
面向向阳花
面向向阳花 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:05

    If you don't call .ToList() the enumerable will be evaluated after your using clause finishes, and thus the data context will be disposed before evaluating the query.

    IMO, you should consider making your repository handle this (by calling .ToList()) as otherwise this issue is representative of an implementation detail leaking out.

提交回复
热议问题