The query results cannot be enumerated more than once?

我们两清 提交于 2019-11-29 01:31:03

Since this is executing a stored procedure, all your lovely Skip / Take is largely redundant anyway... it has no choice but to bring all the data back (stored procedure calls are non-composable). The only thing it can do is not materialize objects for some of them.

I wonder if the better approach would be to refactor the code to make two calls:

int result = repository.FullTextSearchCount(searchText);
var result = repository.FullTextSearch(searchText, skip, take); // or similar

i.e. make the paging parameters part of the SPROC (and to the filtering at the database, using ROW_NUMBER() / OVER(...), or table-variables, temp-tables, etc) - or alternatively something similar with an OUTPUT parameter in the sproc:

int? count = null;
var result = repository.FullTextSearch(searchText, skip, take, ref count);

(I seem to recall that OUTPUT becomes ref, since TSQL OUTPUT is really input+output)

What you can do is add a ToList() call after repository.FullTextSearch(searchText). This way, the results are retrieved from the server, after which you can do with them whatever you want (since they are now loaded in-memory).

What you are trying to do now is run the same SQL query twice, which is rather inefficient.

Sasha

Using ToList() can help to avoid this problem.

var result = repository.FullTextSearch(searchText).ToList();

I would suggest that if you need the count, execute the result first. and then run the count from the list itself, as you don't use resultsCount in your result execution.

var result = repository.FullTextSearch(searchText);
var ret = result.Skip((pageNumber - 1) * PageSize).Take(PageSize).ToList();
int resultsCount = ret.Count();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!