11

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?

Chris Canal
  • 4,824
  • 9
  • 35
  • 45
  • 2
    I think that's the best way to do it. In SQL you'd write: SELECT e.* from e WHERE e.Property = (SELECT MAX(e2.Property) WHERE e2.EnquiryCode = e.EnquiryCode) and that's all you're doing in your HQL. – kͩeͣmͮpͥ ͩ Dec 12 '08 at 15:19
  • Thanks, this helped me with a similar issue (even though you have no answers!) – PandaWood Mar 18 '11 at 06:18

3 Answers3

1

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)...'

Community
  • 1
  • 1
eepzable
  • 153
  • 2
  • 7
1

For aggregations it is better to use SQL and not HQL.Use Nhibernate just for main Entities and their relations (very maintainable design) .Stored procedures are a better place to these aggregations and functions because they are data dependent and not object dependent

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
0

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>()