1

I'm using NHibernate with oracle db and I want to make a query that selects many columns. For example, lets say I have a table named Soldiers with the following columns :

Id, first name and last name.

I want to select and return the first name and last name of all the soldiers, so in sql it will be like this: SELECT FIRSTNAME, LASTNAME FROM SOLDIERS;

How do I do it in code using QueryOver?

1
  • How do I retun a collection that contains both the firstname and last name without creating a new class Commented Nov 9, 2015 at 13:37

1 Answer 1

1

To use QueryOver, there must be mapped class Soldier. That is a must. But then it is easy to use QueryOver to get FirstName and LastName of all:

Soldier soldier = null;
var list = session
    .QueryOver<Soldier>(() => soldier)
    .SelectList(l => l
        .Select(x => x.LastName).WithAlias(() => soldier.LastName)
        .Select(x => x.FirstName).WithAlias(() => soldier.FirstName)
    )
    .TransformUsing(Transformers.AliasToBean<Soldier>())
    // .Take(10) just 10
    .List<Soldier>();

Assert.IsTrue(list.First().FirstName != null);
Assert.IsTrue(list.First().LastName != null);
Sign up to request clarification or add additional context in comments.

4 Comments

Im getting an exception, currect me if im wrong, you are creating a QueryOver from the type Soldier and you get all of the soldiers and then you take only the firstname and lastname, and the result is still list of soldiers? And can you explain what does the transformusing doing?
It just converts the projection, into original entity. Because SelectList is about projection... nhibernate.info/doc/nh/en/index.html#queryqueryover-projections and that must be transformed
Thank you thats really helpfull and exactly what I've been looking for
Enjoy mighty NHibernate, sir ;) It is still amazing tool ;)

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.