简体   繁体   中英

NHibernate Criteria query to select the most recent item per type

I need to find the most recent report submitted by members of staff, using an NHibernate criteria query. I'm sure that I need to use projections, but I can't work out how to set it up.

A paraphrase of my domain model:

public class Employee
{
  public int Id {get; set;}
  public string Name {get; set;}
}

public class Report 
{
  public int Id {get; set;}
  public DateTime? Submitted {get; set;}
  public Employee Employee {get; set;}
  // Other report properties omitted
}

If there were 5 members of staff, who each have 7 reports, the query should return 5 reports, one per employee, with the Submitted property being not null, and being most recent one for that employee .

I am not quite sure about this, but check it out:

var rst = session.CreateCriteria<Report>()
                .SetProjection(Projections.GroupProperty("Employee"))
                .SetProjection(Projections.Max("Submitted"))
                .Add(NHibernate.Criterion.Expression.IsNotNull("Submitted")).List();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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