问题
Consider the following object structure.
Product
id : int
name : string
attribute : list of Attribute
Attribute
id : int
name: string
value : string
product_id : int
The questions is: Using QueryOver how to form a subquery to return all products with the following conditions:
Select all products where when have attributes at the same time:
Attribute name = "Color" Value="Red" and Attribute name = "Size" Value="XXL" ?
Edit: Sample 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)
回答1:
using a subquery which counts the attribute matches is the easiest 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();
The subquery can be shortened if there is a Property Product on the Attribute class
来源:https://stackoverflow.com/questions/12467699/nhibernate-queryover-subquery-and-whereexists-with-2-conditions