Search code examples
c#linqlinq-to-sqlstack-overflow

LINQ query creates a StackOverflow Exception


This is LINQ-to-SQL.

I'm trying to walk up a hierarchical relationship of SiteCategories to see how many levels there are.

int numLevels = 1;

//I tried setting this to new[] { parentID }.AsQueryable(); 
//but linq didn't like it
IQueryable<int> nextBatchOfParents = _catalogdb.SiteCategories
                    .Where(c => c.SiteCategoryId == parentID)
                    .Select(c => c.SiteCategoryId);

while ((nextBatchOfParents = _catalogdb.SiteCategoryRelationships
         .Where(rel => nextBatchOfParents.Any(x => x == rel.ChildSiteCategoryId))
         .Select(rel => rel.ParentSiteCategoryId)).Any())
                ++numLevels;

Unfortunately the first iteration of the loop causes a StackOverflow exception. I'm guessing I could sneak my way out of this by materializing most/all of these queries sooner, but I'm hoping there's a better way to fix this.


Solution

  • It looks like you're calling nextbatchofparents within itself.