LINQ throwing Query nested exception too deep

I have the following class and objects

Product{int ProdId{get; set;}, string ProdDesc{get; set;}}

IQueryable<Product> products = ProductRepository.GetAllProducts();

List<int> filteredProdIds = new List<int>();


The method GetAllProducts()

performs a couple of joins on some EF classes and returns an object IQueryable<Product>

. I've already tested if it returns the expected values โ€‹โ€‹and does it.

From products

I want to get all the records that have ProdId

in filteredProdIds

(assume filteredProdIds

already filled with using Ids


products = products.Where(p => filteredProdIds.Any(fp => fp.Equals(p.ProdId)));


When I run my application it throws an exception

Some of your SQL statement is nested too deeply. Rewrite the query or split it into smaller queries.

I tried to validate the query using LINQPad replacing the method with the GetAllProducts()

equivalent database viewand it works.

What could be the cause of this exception?


filterProductIds is populated using this method:

IEnumerable<int> filteredProductIds = products.Select(p => p.partId).Distinct().ToList();


I found a way to avoid this exception, but there should be a much cleaner solution:

foreach (var filteredProdId in filteredProdIds)
   product.Union(product.Where(p => p.ProdId.Equals(filteredProdId)));



source to share

2 answers

There is a limit on the number of items in filteredProdIds

, since this is a list.

To check, you can install filteredProdIds


filteredProdIds = filteredProdIds.Take(1).ToList();




var filteredProdIds = FilterIds().ToArray();
var products = ProductRepository.GetAllProducts().Where(p => filteredProdIds.Contains(p.ProdId));




All Articles