Search code examples
nhibernatefluent-nhibernate

What exactly is a Cartesian product in NHibernate?


I often hear the word "Cartesian Product" from my co-workers when there's a Domain Model with a collection in a collection and eager fetch of the same. Let's say I have the below Model.

public class Order{
  List<Product> Products
}
public class Product{
  List<Units> Units
}

Now they say, If I try to Eager fetch Order with Products and Units, I'm supposed to get a Cartesian Product (aka duplicates ..). But when i test it by enabling ShowSql I don't seem to get any duplicates. This is my repository class

    public List<Order> GetOrdersWithProductsAndUnits()
    {
        return GetSession().Query<Order>()
                           .FetchMany(order => order.Products)
                           .ThenFetch(product => product.Units)
                           .ToList();
    } 

And here's the sql output on enabling ShowSql. This seems fine and as expected with the join on the necessary tables.

select order0_.Id as Id8_0_, 
childstock1_.Id as Id23_1_,
childstock2_.Id as Id24_2_, 
order0_.CustomerName as Customer2_8_0_,  
order0_.City as City8_0_,
childstock1_.Size as Size23_1_,
childstock2_.Box as Box24_2_,
from Orders order0_  
left outer join Products childstock1_ on order0_.Id=childstock1_.OrderId  
left outer join Units childstock2_ on childstock1_.Id=childstock2_.ProductId

I had 125 Orders in my Database and when i eager fetch the orders with the Products and Units I still get 125 records.

List<Order> orders = repository.GetOrdersWithProductsAndUnits();
   Assert.That(orders.Count,Is.EqualTo(125));

Further when i check via the Visual Studio Debugger I don't find any duplicates inside the Order Collection at Products or Units level either.

I was expecting as many Orders as Units in my Database(close to 1000) because of a cartesian product resulting in duplicates. Am I missing something trivial, Is my understanding of Cartesian product skewed ? Or does the Query API that I'm using automatically solves Cartesian Products problem automatically.

FYI: I'm sure of the data setup as well. I've debugged through the Visual Studio Debugger and I notice Orders that have more than one Products and Products with more than one Units.

Any help/reference material is appreciated.

Thanks


Solution

  • In contrast to other query types (HQL, Criteria, QueryOver) NHibernate automatically discards duplicate root entities in Linq queries. But as you said in your last comment, you still get that many rows from the database, so your query might be slow.