NP0004: A recursive method runs a query on every call
Default severity: Warning
What it detects
A method that runs a query and calls itself, outside a loop, so walking a chain or a tree costs one round trip per level:
public async Task<int> Depth(int categoryId)
{
var category = await db.Categories.FirstAsync(c => c.Id == categoryId);
return category.ParentId is null ? 0 : 1 + await Depth(category.ParentId.Value); // NP0004
}
Recursion through another method counts too (Depth calls ParentDepth, which queries and calls Depth). It is
reported once, at the call made by the method that runs the query itself.
When the recursive call is inside a loop (one call per child), the call is reported as NP0001 instead.
How to fix it
Load all rows of the tree in one query and link them in memory, or let the database walk it with a recursive common
table expression (FromSql/SqlQuery).