我相信这应该有效。我没有在本地数据库上尝试过,但应该让你朝着正确的方向前进。
Product product = null;
Store store = null;
Chain chain = null;
//01. Load Products from Store
var productsFromStores
= QueryOver.Of(() => product)
.JoinAlias(() => product.Stores, () => store)
.Where(() => store.Id == searchCriteria.StoreId)
.Select(Projections.Distinct(Projections.Id()));
//02. If Chain DOES NOT refer Store
var productFromChains
= QueryOver.Of(() => store)
.JoinAlias(() => store.Chain, () => chain)
.JoinAlias(() => chain.Products, () => product)
.Where(() => store.Id == StoreId)
.Select(Projections.Distinct(
Projections.Property(() => product.Id)));
//03. Load Products from present either in the Store and or the chains
var products
= session.QueryOver(() => product)
.Where(
Restrictions.Or(
Subqueries.WhereProperty(() => product.Id)
.In(productsFromStores),
Subqueries.WhereProperty(() => product.Id)
.In(productFromChains)));
仅供参考:请注意,这可能不是处理您的查询的最理想方式。当我看到使用IN ()
和子查询时,我总是畏缩不前。
如果 Chain 中确实有一个 Store,那么 //02 可以写成
//Load Products from Chains
//02. If Chain DOES refer to a Store
var productFromChains
= QueryOver.Of(() => chain)
.JoinAlias(() => chain.Store, () => store)
.JoinAlias(() => chain.Products, () => product)
.Where(() => store.Id == searchCriteria.StoreId)
.Select(Projections.Distinct(
Projections.Property(() => product.Id)));