I just started playing with NHibernate Linq and found a strange behavior. I have a class Category and a class Product. Category has a list of Products with one to many association. Here’s mappings:
<class name="Category">
<id name="Id">
<generator class="hilo" />
</id>
<property name="Name" lazy="false" length="20" />
<bag name="Products" cascade="none" lazy="false" inverse="true" fetch="join">
<key column="CategoryId" />
<one-to-many class="Product" />
<!--<filter name="IdFilter" />-->
</bag>
</class>
<class name="Product">
<id name="Id">
<generator class="hilo" />
</id>
<property name="Name" lazy="false" />
<property name="Discontinued" lazy="false" />
<property name="Price" lazy="false" />
<many-to-one name="Category"
class="Category"
column="CategoryId"
cascade="none" />
</class>
When I query categories with this query
var cs = session.Query<Category>().Where(c => c.Products.Any(p => p.Price == 13.3392)).ToList();
I look at NHibernate profiler and see this results
select category0_.Id as Id1_,
category0_.Name as Name1_
from Category category0_
where exists (select products1_.Id
from Product products1_
where category0_.Id = products1_.CategoryId
and products1_.Price = 13.3392 /* @p0 */)
SELECT products0_.CategoryId as CategoryId1_,
products0_.Id as Id1_,
products0_.Id as Id0_0_,
products0_.Name as Name0_0_,
products0_.Discontinued as Disconti3_0_0_,
products0_.Price as Price0_0_,
products0_.CategoryId as CategoryId0_0_
FROM Product products0_
WHERE products0_.CategoryId = 131073 /* @p0 */
SELECT products0_.CategoryId as CategoryId1_,
products0_.Id as Id1_,
products0_.Id as Id0_0_,
products0_.Name as Name0_0_,
products0_.Discontinued as Disconti3_0_0_,
products0_.Price as Price0_0_,
products0_.CategoryId as CategoryId0_0_
FROM Product products0_
WHERE products0_.CategoryId = 32768 /* @p0 */
The category is fetched one by one from database. So the amount of roundtrips to database equals to the amount of category objects matched by where clause.
Is there a way to tell NHibernate to optimize the query? I’m completely lost.
Thank you very much for your support.
on your bag mapping class try adding
batch-size