1

考虑以下对象结构。

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)
4

1 回答 1

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();

如果 Attribute 类上有 Property Product,则可以缩短子查询

于 2012-09-19T13:06:57.450 回答