Nhibernate Queryover subquery and whereexists with 2 conditions

给你一囗甜甜゛ 提交于 2019-12-24 17:40:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!