4

I have an application using NHibernate and C# language. I have an model with some relations and I want to create a query to get only one value. I've tried something like this:

public long GetIdCompany(long number)
{
    return session.QueryOver<Report>()
                  .Where(x => x.Number == number)
                  .Select(x => x.Equipament.Company.Id)
                  .Take(1);
}

but I didn't work. I just want to take the IdCompany in the the model Report.Equipament.Company.Id. It could be in queryover, linq, hql, etc...

2
  • As a side, you could probably shorten this to .Where(x => x.Number == number).Single().[Id prop] Commented Jul 27, 2012 at 12:58
  • what is not working ? can you show us an error message ? Commented Jul 27, 2012 at 13:05

2 Answers 2

9

You should use JoinAlias, so your request will looks like

    public long GetIdCompany(long number)
    {
        Equipament equipamentAlias = null;
        return session.QueryOver<Report>()
                      .Where(x => x.Number == number)
                      .JoinAlias(x => x.Equipament, () => equipamentAlias)
                      .Select(x => equipamentAlias.Company.Id)
                      .SingleOrDefault<long>();
    }

Here is excellent introduction to QueryOver

Sign up to request clarification or add additional context in comments.

Comments

8

HQL

return session.CreateQuery(
        "select e.Company.id from Report r " +
        "    inner join r.Equipament e " +
        "where r.Number = :number")
    .SetInt64("number", number)
    .UniqueResult<long>();

LINQ

return session.Query<Report>()
    .Where(x => x.Number == number)
    .Select(x => x.Equipament.Company.Id)
    .Single();

QueryOver

See GSerjo's answer.

2 Comments

@GSerjo Thanks. Pointed to your answer.
Thank you Miroslav, I liked your awser but I would like to use QueryOVer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.