简体   繁体   English

当属性等于Max with NHibernate时选择对象

[英]Select object when a property equals Max with NHibernate

We have a query that selects rows depending on the value of another, ie. 我们有一个查询,根据另一个的值选择行,即。 the max. 最大 I don't think that really makes much sense, so here is the query: 我认为这没有多大意义,所以这里是查询:

var deatched = DetachedCriteria.For<Enquiry>("e2")
   .SetProjection(Projections.Alias(Projections.Max("Property"), "maxProperty"))
   .Add(Restrictions.EqProperty("e2.EnquiryCode", "e.EnquiryCode"));

session.CreateCriteria(typeof(Enquiry), "e")
   .Add(Subqueries.PropertyEq("Property", deatched))
   .AddOrder(Order.Asc("EnquiryCode"));

My question is, is this the best way? 我的问题是,这是最好的方法吗? Can anyone suggest a better way? 有谁能建议更好的方法?

You should be able to do this with projection: 您应该可以通过投影执行此操作:

session.CreateCriteria(typeof(Customer))
  .SetProjection( Projections.Max("Id") )
  .UniqueResult();

As described Nhibernate Criteria: 'select max(id)...' Nhibernate Criteria所述:'select max(id)...'

对于聚合,最好使用SQL而不是HQL。使用Nhibernate仅用于主要实体及其关系(非常易于维护的设计)。存储过程是这些聚合和函数的更好位置,因为它们依赖于数据而不依赖于对象

I think this must work: 我认为这必须奏效:

(from e in NHibernateSession().Query<Enquiry>()
    where e.Property == (
    (
        from e2 NHibernateSession().Query<Enquiry>()
        where e2.EnqueryCode == e.EnquiryCode
        select e2.Property).Max()
    )
    select e
).ToList<Enquiry>()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM