I am trying to prevent my methods returning all rows from large table if user did not pass filter to method. Now I doing something like this
public IQueryable<Doc> grids (string filter)
{
int all = int.MaxValue;
if (string.IsNullOrEmpty(filter))
all = 5;
return rampa.Doc.Where(x => x.Napomena.Contains(filter)).Take(all);
}
Is there a nicer way to avoid take extension conditionally. I do not want to burden SQL server whit unnecessarily top clue.
One of basic requirement of using Take()
is you have to use OrderBy
with it. Then to avoid top(int.max)
write your query as follow:
public IQueryable<Doc> grids (string filter)
{
IQueryable<Doc> query = rampa.Doc;
if (string.IsNullOrEmpty(filter))
{
query.Where(x => x.Napomena.Contains(filter)).Orderby(x => x.OrderByColumn).Take(5);
}
return query;
}