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

Rol*_*and 2 .net fluent-nhibernate queryover

考虑以下对象结构。

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

Attribute
id : int
name: string
value : string
product_id : int
Run Code Online (Sandbox Code Playgroud)

问题是:使用 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)
Run Code Online (Sandbox Code Playgroud)

Fir*_*iro 5

在我看来,使用计算属性匹配的子查询是最简单的

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();
Run Code Online (Sandbox Code Playgroud)

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