Home > Backend Development > C++ > How to Retrieve Requests with the Latest Successful Response Using NHibernate?

How to Retrieve Requests with the Latest Successful Response Using NHibernate?

Susan Sarandon
Release: 2025-01-15 06:35:43
Original
793 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template