LINQ query creates a StackOverflow Exception

2019-09-19 08:53发布

问题:

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.

回答1:

It looks like you're calling nextbatchofparents within itself.