NHibernate:从子查询创建条件

时间:2014-09-02 12:06:30

标签: c# sql nhibernate

拥有SQL:

select COUNT(1) from
(SELECT TOP 10 Status
FROM SESSIONS
where SERVER_ID = 2569
ORDER by ID desc) as s
where s.STATUS = 32768

如何在NHiberbate中创建Criteria?语言C#。

        var subQuery = DetachedCriteria.For(typeof(Session))
            .SetProjection(Property.ForName("Status"))
            .Add(Restrictions.Eq("Server", server))
            .AddOrder(Order.Desc("Id"))
            .SetMaxResults(10);
        var query = DetachedCriteria.For(typeof(Session))
            .Add(Subqueries.Exists(subQuery))
            .Add(Restrictions.Eq("Status.Id", valueFailStatus))
            .SetProjection(Projections.RowCount());
        using (var session = NHibernateHelper.OpenSession())
            return (int)query.GetExecutableCriteria(session)
            .UniqueResult();

但是我得到了整个表的样本,而不是这10个元素中的一个。

1 个答案:

答案 0 :(得分:2)

现在,只要此子查询返回任何结果,您的查询就会显示 Session StatusId valueFailStatus

由于您使用的是Exists,因此您并未将查询关联在一起以执行您想要的操作。

我认为你正在寻找Subqueries.PropertyIn。像这样:

var subQuery = DetachedCriteria.For(typeof(Session))
    .SetProjection(Property.ForName("Id"))
    .Add(Restrictions.Eq("Server", server))
    .AddOrder(Order.Desc("Id"))
    .SetMaxResults(10);

var query = DetachedCriteria.For(typeof(Session))
    .Add(Subqueries.PropertyIn("Id", subQuery))
    .Add(Restrictions.Eq("Status", 32768))
    .SetProjection(Projections.RowCount());

var result = (int)query.GetExecutableCriteria(s)
    .UniqueResult();

...将生成如下所示的SQL:

SELECT
    count(*) as y0_ 
FROM
    Sessions this_ 
WHERE
    this_.Id in (
        SELECT
            TOP (10) this_0_.Id as y0_ 
        FROM
            Sessions this_0_ 
        WHERE
            this_0_.Server_Id = 2569
        ORDER BY
            this_0_.Id desc
    ) 
    and this_.Status = 32768