Ok, this should be really simple. I'm new to NHibernate, but everywhere I've searched has given me conflicting answers on this, and none of them seem to work. Basically, I need to implement the following SQL query into my code. It simply returns the most recent records for a specific participant.
select *
from result
where ParticipantId = 1
and ResultDate = (select MAX(resultDate)
from Result
where ParticipantId = 1)
I'm using Fluent NHibernate with NHibernate 3.3. I can pull back the data without the "and" in the where clause using the code below, but when I try to restrict it to the most recent records, nothing's working.
var resultSet = session.Query<Result>()
.Where(r => r.Participant.ParticipantId == 1);
Also including my domain and mapping files here for completeness. Let me know if more info is needed.
public class Result
{
public virtual int ResultId { get; set; }
public virtual Participant Participant { get; set; }
public virtual ResultType ResultType { get; set; }
public virtual float? ResultValue { get; set; }
public virtual string ResultText { get; set; }
public virtual DateTime ResultDate { get; set; }
public virtual int? Systolic { get; set; }
public virtual int? Diastolic { get; set; }
public virtual DateTime? DateAdded { get; set; }
public virtual string AddedBy { get; set; }
public virtual DateTime? DateChanged { get; set; }
public virtual string ChangedBy { get; set; }
}
public ResultMap()
{
Table("Result");
LazyLoad();
Id(x => x.ResultId).GeneratedBy.Identity().Column("ResultId");
References(x => x.Participant).Column("ParticipantId");
References(x => x.ResultType).Column("ResultTypeId");
Map(x => x.ResultValue).Nullable();
Map(x => x.ResultText).Nullable().Length(100);
Map(x => x.ResultDate).Nullable();
Map(x => x.Systolic).Nullable();
Map(x => x.Diastolic).Nullable();
Map(x => x.DateAdded).Nullable();
Map(x => x.AddedBy).Nullable().Length(100);
Map(x => x.DateChanged).Nullable();
Map(x => x.ChangedBy).Nullable().Length(100);
}
Any thoughts on an easy solution to get the recent data? Bonus points for letting me know how to get the last 2 dates, as I'll need them soon for comparing improvements. Thanks in advance!
To get that same query via QueryOver...
var maxResultDate = QueryOver.Of<Result>()
.Where(x => x.Participant.ParticipantId == 1)
.Select(Projections.Max<Result>(x => x.ResultDate));
var rslt = s.QueryOver<Result>()
.Where(x => x.Participant.ParticipantId == 1)
.WithSubquery.WhereProperty(x => x.ResultDate).Eq(maxResultDate)
//or to get the "last" 2 rows...
//.OrderBy(x => x.ResultDate).Desc
//.Take(2)
.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.