2013-03-24 64 views
1

這裏是我的域模型的一小摘錄:查詢過一種不同的實體

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

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

現在我需要在Store相關Chain創造了Product查詢。 問題是如何擴展存儲在所有者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

+0

這將是*更*有益的,如果你可以的,你要查詢的,而不是描述QueryOver什麼純英文定義查詢。 – frictionlesspulley 2013-04-07 15:51:13

+0

奧克我試圖把重點放在更具體的問題上。我希望我的問題現在變得更加清晰。 – core 2013-04-08 18:15:19

+0

如果您可以指定查詢嘗試執行的示例,那肯定會有所幫助。 – frictionlesspulley 2013-04-08 18:24:51

回答

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()和子查詢時,我總是畏縮。

如果鏈確實有一個商店在其隨後// 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))); 
+0

經過一些試驗,我現在有解決方案。我會分開發布它。感謝您推動正確的方向! – core 2013-04-10 19:25:06