Home >Backend Development >C++ >How to Retrieve Requests with the Latest Successful Response Using NHibernate?
HasMany Query: Get the request with the latest successful response
Consider the following solid model:
<code class="language-c#">public class Request { public virtual IList<Response> Responses { get; set; } } public class Response { public virtual DateTime Timestamp { get; set; } public virtual bool Success { get; set; } }</code>
The task is to construct a query that retrieves all successful requests with the latest response (based on timestamp).
NHibernate solution using QueryOver
NHibernate provides a comprehensive solution using QueryOver:
<code class="language-c#">Response responseAlias = null; var maxSubquery = QueryOver.Of<Response>() .SelectList(l => l .SelectGroup(item => item.RequestId) .SelectMax(item => item.Timestamp) // 使用 Timestamp 而不是 DateTime ) .Where(item => item.RequestId == responseAlias.RequestId) .Where(Restrictions.EqProperty( Projections.Max<Response>(item => item.Timestamp), // 使用 Timestamp 而不是 DateTime Projections.Property(() => responseAlias.Timestamp) // 使用 Timestamp 而不是 DateTime )); var successSubquery = QueryOver.Of<Response>(() => responseAlias) .Select(res => res.RequestId) .WithSubquery .WhereExists(maxSubquery) .Where(success => success.Success == true); var query = session.QueryOver<Request>(); query.WithSubquery .WhereProperty(r => r.ID) .In(successSubquery); var list = query.List<Request>();</code>
This query retrieves all requests that had at least one successful response (most recent based on timestamp). DateTime
has been replaced with the more accurate Timestamp
in the code, and variable naming has been slightly adjusted to improve readability. The core logic remains the same.
The above is the detailed content of How to Retrieve Requests with the Latest Successful Response Using NHibernate?. For more information, please follow other related articles on the PHP Chinese website!