Using split queries (AsSplitQuery) in Entity Framework Core to avoid the cartesian explosion problem

Without lazy loading in Entity Framework Core we must eagerly load related entities which means we can experience the ‘cartesian explosion’ problem. This relates to how we can get lots of duplicated data for each join we do. Mostly this duplicated data is handled fine but if there is enough of it, it can affect performance.

One possible resolution for the ‘cartesian explosion’ problem is to split the queries up when serving them against the DB and join the result sets back on the client side. As of version 5.0 query splitting is possible in Entity Framework Core with the AsSplitQuery extension method. The syntax is simple…

AsSplitQuery in EF Core 5.0

In the 1st example below (click the image for a larger view in a new window) we can see the EF Core default which is to issue a single query which left joins blogs and posts. We can see some duplicated data highlighted in red. In this case we only have a small amount of duplication as we are only joining one table and it is quite narrow without many columns.

In the 2nd example below¬†we include the new .AsSplitQuery() syntax and can see that this produces two queries and two result sets which EF Core will combine. Two potential issues with using AsSplitQuery() include…

Data can change in between the first and second queries. Consider using transactions to mitigate this.

More roundtrips due to multiple queries. If latency is high this can affect performance. Consider using MARS to potentially help here if using SQL Server.

Using Entity Framework Core 5.0 split queries

Leave a Reply

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