1

这是我的域模型的一小部分摘录:

public class Chain
{
    public IList<Product> Products { get; set; }
}

public class Store
{
    public Chain Chain { get; set; }
    public IList<Product> Products { get; set; }
}

现在我需要在ProductinStore 关联的Chain. 问题是如何扩展对存储在所有物中的产品的查询Chain

这是我到目前为止所拥有的:

var subQuery = QueryOver.Of<Store>()
    .Where(s => s.Id == searchCriteria.StoreId)
    .Select(s => s.Id);

Store storeAlias = null;
var query = _session.QueryOver<Product>()
    .JoinAlias(p => p.Stores, () => storeAlias)
    .WithSubquery.WhereProperty(() => storeAlias.Id).In(subQuery);
    //// some more clauses...

我怎样才能做到这一点?请注意:Chain财产Store可能是null.

4

1 回答 1

1

我相信这应该有效。我没有在本地数据库上尝试过,但应该让你朝着正确的方向前进。

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)));
于 2013-04-08T19:26:54.500 回答