Search code examples
c#nhibernateoracle10gqueryover

Multiple columns query - Nhibernate using QueryOver


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?


Solution

  • 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);