In a project I have to maintain, I have this Linq query using Take(1)
:
(from workflow in db.Workflows
from search in db.Searches.Where(p => p.WorkflowId == workflow.WorkflowId).Take(1).DefaultIfEmpty()
select new { workflow, hasSearch = search.SearchId > 0 }).ToList();
When Take(1)
is translated to SQL, it gives something like :
ROW_NUMBER() OVER(PARTITION BY WorkflowId ORDER BY WorkflowId)
which occurs to be lacking performance.
I guess the developer had a SELECT TOP 1
in mind. But if use FirstOrDefault
it would not return an IQueryable anymore. So, my question is : how can I rewrite the Linq query to keep the same purpose and not using Take
, if possible ?
CodePudding user response:
If understand correctly needed result, query should be rewritten in this way:
var query =
from workflow in db.Workflows
select new
{
workflow,
hasSearch = db.Searches.Any(p => p.WorkflowId == workflow.WorkflowId)
};