2
我剛開始玩NHibernate Linq,發現一個奇怪的行爲。我有一個班級類別和一個班級產品。類別包含具有一對多關聯的產品列表。這裏的映射:NHibernate Linq。查詢關聯和多個SQL查詢
<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>
當我查詢的類別與此查詢
var cs = session.Query<Category>().Where(c => c.Products.Any(p => p.Price == 13.3392)).ToList();
我看NHibernate的探查,看到這個結果
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 */
類別是一個從數據庫中獲取一個。所以到數據庫的往返數量等於where子句匹配的類別對象的數量。
有沒有辦法告訴NHibernate優化查詢?我完全失去了。
非常感謝您的支持。
你能後的全品類映射? – Vadim 2011-01-22 18:21:30
我發現了一個更好的解決方案,可以從linq加載。如果有人感興趣看看[這裏](http://mikehadlow.blogspot.com/2010/08/nhibernate-linq-eager-fetching.html) – Davita 2011-01-23 13:13:06