在 C# 程序停止枚举后,从 IQueryable 生成的 SQL 查询是否继续执行?

Does the SQL query generated from an IQueryable continue to execute after the C# program stops enumerating?

我有一个包含大量记录的数据库。我有无法翻译成 SQL 的记录过滤条件。考虑以下情况:

IItemRepository repo = new ItemRepository();
IQueryable<Item> items = repo.GetAll();
IEnumerator<Item> itemEnumerator = items.GetEnumerator();
List<BinaryData> binaryDataList = new List<BinaryData>();

while (binaryDataList.Count < 20 && itemEnumerator.MoveNext())
{
    BinaryData binaryData = BinaryData.Extract(itemEnumerator.Current.BinaryData);

    if (IsValidBinaryData(binaryData))
    {
        binaryDataList.Add(binaryData);
    }
}

一旦程序退出while循环,查询是继续在服务器上执行还是停止?我需要它停止,因为在这个数据库上执行 GetAll() 查询会很疯狂。

编辑: 我把场景简化了,在实际情况下有一些过滤器和排序,但是复制和粘贴那些复杂的代码没有意义。

分页是处理许多结果的好方法。

您的评论表明您了解 TakeSkip

Implement Efficient Data Paging 有一个完整的例子。这是它的一小部分。

public IQueryable<Dinner> FindUpcomingDinners() 

(...)

var upcomingDinners = dinnerRepository.FindUpcomingDinners();

var paginatedDinners = upcomingDinners.Skip((page ?? 0) * pageSize)
                                         .Take(pageSize)
                                         .ToList();

(...)

Entity Framework is smart enough to construct an optimized SQL query that performs this skipping logic in the SQL database – and not in the web-server. This means that even if we have millions of upcoming Dinners in the database, only the 10 we want will be retrieved as part of this request (making it efficient and scalable).


问题

Once the program exits the while loop, does the query continue to execute on the server or does it stop? I need it to stop, because executing a GetAll() query on this database would be madness.

没有'continuing'执行查询。当枚举 IQueryable 时,代码 not 一条一条地获取记录。在枚举点,查询被发送到数据库,所有结果被提取然后存储在内存中。