Adam Rackis
Adam Rackis

Reputation: 83356

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.

Upvotes: 0

Views: 227

Answers (1)

McKay
McKay

Reputation: 12604

It looks like you're calling nextbatchofparents within itself.

Upvotes: 3

Related Questions