LINQ query creates a StackOverflow Exception

元气小坏坏 提交于 2020-01-06 12:41:52

问题


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.



来源:https://stackoverflow.com/questions/8126328/linq-query-creates-a-stackoverflow-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!