NHibernate的Queryover子查询和whereexists带2分的条件(Nhiberna

2019-09-30 04:32发布

考虑下面的对象结构。

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

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

这些问题是:用QueryOver如何形成一个子查询返回所有产品符合下列条件:

选择其中具有在同一时间属性时,所有的产品:

属性名= “COLOR” VALUE = “红”,属性名= “大小” 值= “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)

Answer 1:

利用它计算子查询的属性相匹配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();

如果在属性类的属性产品中的子查询可缩短



文章来源: Nhibernate Queryover subquery and whereexists with 2 conditions