An alternative to NHibernate UniqueResult?

We are using NHibernate in a project that pulls data from a database and writes reports to a separate system. In my scenario, the patient usually, but not always, has the next appointment when the report is written. The next query gets the following assignment details to include in the report.

private NextFollowup GetNextFollowup(int EncounterID)
    {
        try
        {
            NextFollowup myNextF = new NextFollowup();

            IQuery myNextQ = this.Session.GetNamedQuery("GetNextFollowup").SetInt32("EncounterID", EncounterID);

            myNextF = myNextQ.UniqueResult<NextFollowup>();

            return myNextF;

        }
        catch (Exception e)
        {
            throw e;
        }

    }

      

Here's the question:

This usually works great, since assignment assigns one result. However, in cases where there is no next follow-up, I get the error that there is no unique result. In this case, I really don't want to throw an exception, I want to return an empty object. If I got a list instead of a UniqueResult, I would get an empty list in situations where there is no subsequent update. Is there a better way to handle the "when there is a value, there will be only one" situation than using a list in an HQL query?

+3


source to share


1 answer


This might work:

private NextFollowup GetNextFollowup(int encounterID)
{
    IQuery query = this.Session.GetNamedQuery("GetNextFollowup").SetInt32("EncounterID", encounterID);

    // nextFollowup will be either the next instance, or null if none exist in the db.
    var nextFollowup = query.Enumerable<NextFollowup>().SingleOrDefault();

    return nextFollowup;
}

      

Note: Updated title to follow Microsoft guidelines.



The try catch serves no purpose here, other than to lose the stack trace if there is an exception, so I removed it.

If you want to return a new NextFollowup if it doesn't exist, you can update the query string to:

var nextFollowup = query.Enumerable<NextFollowup>().SingleOrDefault() ?? new NextFollowup();

      

+2


source







All Articles