Code First Entity Framework – Some part of your SQL statement is nested too deeply. Rewrite the query or break it up into smaller queries

While I was working on EF I encountered a funny exception:

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

At first I did not know why it was throwing this exception, so I decided to see/inspect the query that was being build in the context.

Turns out the query was a total mess, it was nesting a lot of SQL, the scrollbar was so small… so something was wrong.

The query had a .Any in it which forces the DbContext to build a query with nested sql.

To fix this error remove the

.Any

And Convert it to

.Contains — Contains is converted into an IS IN SQL Statement

The query now looks much smaller… So if you encounter this error look for .Any in your query and convert it to a .Contains

Leave a Reply

Your email address will not be published. Required fields are marked *