NHibernate Projections and “Having” clause

泄露秘密 提交于 2019-12-22 05:54:47

问题


I'm using NHibernate to query my database with the criteria API. My criteria is below:

ICriteria c = Session.CreateCriteria(typeof(Transaction));

ProjectionList projections = Projections.ProjectionList();
projections.Add(Projections.Sum("Units"), "Units");
projections.Add(Projections.GroupProperty("Account"), "Account");
projections.Add(Projections.GroupProperty("Security"), "Security");
c.SetProjection(projections);

This is working fine, but what I would like is a way to be able to limit the query to only return when the "Units" property is > 0. In SQL I would simply us a Having Units > 0 clause however I haven't been able to find a way to do this in NHibernate. Does anyone have any ideas or is my only option to use HQL?


回答1:


You can access the ProjectionCriteria from the Criteria object.

...
c.SetProjection(projections)
.ProjectionCriteria
.Add(Restrictions.Ge("Units", 0));

EDIT: This solution doesn't currently work, however it should work in NHibernate 2.1.0




回答2:


For whomever drops by here with a similar problem, I just solved it this way:

IProjection howMany = Projections.Count("Id").As("HowMany");

ICriteria criteria = session
    .CreateCriteria<L10N>()
    .SetProjection(
        howMany,
        Projections.GroupProperty("Native"),
        Projections.GroupProperty("Locale")
    );

criteria.Add(Restrictions.Gt(howMany,1));


来源:https://stackoverflow.com/questions/636925/nhibernate-projections-and-having-clause

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