Nhibernate Queryover子查询和whereexists有2个条件

时间:2012-09-17 21:59:37

标签: .net fluent-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)

1 个答案:

答案 0 :(得分: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();

如果属性类

上有属性产品,则可以缩短子查询