簡體   English   中英

NHibernate查詢最新記錄

[英]NHibernate query for most recent records

好的,這應該很簡單。 我是NHibernate的新手,但是在我搜索過的所有地方都給了我與此矛盾的答案,而且似乎都沒有用。 基本上,我需要在代碼中實現以下SQL查詢。 它僅返回特定參與者的最新記錄。

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

我在NHibernate 3.3中使用Fluent NHibernate。 我可以使用下面的代碼在where子句中不使用“ and”來提取數據,但是當我嘗試將其限制為最新記錄時,則無濟於事。

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個日期,因為我很快就會需要它們來比較改進。 提前致謝!

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM