NHibernate查询最新记录

时间:2013-04-11 19:36:16

标签: c# .net sql nhibernate

好的,这应该很简单。我是NHibernate的新手,但我搜索到的所有地方都给了我相互矛盾的答案,而且它们似乎都没有用。基本上,我需要在我的代码中实现以下SQL查询。它只返回特定参与者的最新记录。

select *
from result
where ParticipantId = 1
and ResultDate = (select MAX(resultDate)
                  from Result
                  where ParticipantId = 1)

我使用Fluent NHibernate和NHibernate 3.3。我可以在没有"和"的情况下撤回数据。在where子句中使用下面的代码,但当我尝试将其限制为最新的记录时,没有任何工作。

var resultSet = session.Query<Result>()
.Where(r => r.Participant.ParticipantId == 1);

此处还包括我的域名和映射文件以保证完整性。如果需要更多信息,请告诉我。

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);
}

有关获取最新数据的简单解决方案的任何想法?奖励积分让我知道如何获得最后2个日期,因为我很快就会需要它们来比较改进。提前谢谢!

1 个答案:

答案 0 :(得分:5)

通过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();