What is the Cartesian Explosion in EF Core?

An entity framework is an ORM that makes developer’s lives easier. Using EF, we can interact with the database and perform CRUD operations using a programming language (C#, VB.net). In this blog, we are going to discuss the cartesian explosion in regards to loading data.

Cartesian Explosion

It is related to performing joins. When you perform a join, one table’s columns repeat the X number of times of the matched records from the joined table.

var customers = context.customers
.include(a => a.address)
.ToList();

The LINQ query in SQL:

Select * From Customers
 Left Join Address 
 on Address.Id = Customers.AddressId
Customer IdAddress Details
11
12
…..…..
1500

You can see, the columns of the customer table are repeated 500 times. Now, imagine if you are working on a complex dataset where you have to add a few more includes. The returned data set would explode – it is known as the cartesian explosion.

on-to-the-next-project

Solution

The solution to this is that you split the queries and get data two data sets, rather than one. It would result in two database round trips but would improve performance (fewer reads and CPU time)

var customers = context.customers.ToList();

var addresses = context.addresses.ToList();

Conclusion

In this blog, we discussed what is the cartesian explosion in EF’s eager loading data pattern. You have to be very careful about when to avoid this problem. It is recommended to use the split query approach when the dataset is too large and requires optimization. Otherwise, in normal scenarios include would do the job.

Leave a Reply

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