2012-09-17 50 views
1

請考慮以下對象結構。具有2個條件的Nhibernate Queryover子查詢和預查詢者

Product 
id : int 
name : string 
attribute : list of Attribute 

Attribute 
id : int 
name: string 
value : string 
product_id : int 

的問題是: 使用QueryOver如何形成一個子查詢返回所有產品 具備以下條件:

選擇,其中有在同一時間屬性時,所有的產品:

屬性名稱=「顏色」值=「紅色」 和 屬性名稱=「大小」值=「XXL」?

編輯: SQL示例:

select * from Product p where 
exists (select id from attribute where name = 'Color' and value = 'Red' and product_id = p.id) 
and 
exists (select id from attribute where name = 'Size' and value = 'XXL' and product_id = p.id) 
+0

你會如何在sql中寫這個查詢?除非你不熟悉sql,否則我通常會這樣做。 –

+0

它需要爲每個屬性有一個子查詢。表現不好。 – Roland

+0

@Roland:是的,你可以寫你想要的SQL嗎?這會讓問題更容易回答。 –

回答

4

使用,其對屬性匹配的子查詢IMO

Product productAlias = null 

// get the count of matching Attributes 
var subquery = QueryOver.Of<Product>() 
    .Where(p = > p.Id == productAlias.Id) 
    .JoinQueryOver(p => p.Attributes) 
     .Where(a => (a.Name == "Color" && a.Value == "Red") || (a.Name == "Size" && a.Value == "XXL")) 
    .Select(Projections.RowCount()); 

// get the Products where all match 
var results = session.QueryOver(() => productAlias) 
    .WithSubquery.WhereValue(2).Eq(subquery) 
    .List(); 

如果有物業產品上的子查詢可縮短最簡單屬性類

+0

我不能看到這個過載。那是什麼版本? 。Where(2,subquery) – Roland

+0

這是一個錯字,我會修復 – Firo