What is Cartesian Explosion in Entity Framework?

Experience Level: Senior
Tags: Entity Framework

Answer

Cartesian Explosion is a performance issue that can occur in Entity Framework when you use the Include method to load related data. It happens when you include multiple levels of related data and the number of records returned by the query grows exponentially. This can lead to slow performance and increased memory usage.

To avoid Cartesian Explosion, you can use one of the following methods:

Use Select instead of Include to retrieve only the data you need.

Use AsSplitQuery method to split the query into multiple smaller queries.

Use AsSingleQuery method to execute the query as a single SQL statement.

Here’s an example of how to use AsSplitQuery method:

var orders = context.Orders

    .Include(o => o.Customer)

        .ThenInclude(c => c.Address)

    .AsSplitQuery()

    .ToList();

This code retrieves all orders, their associated customers, and the addresses of those customers in multiple queries.

Entity Framework Core
Entity Framework Core

Are you learning Entity Framework ? Try our test we designed to help you progress faster.

Test yourself