15

How can you get a single column back from a query instead of a whole object?

I could do something like this to get the whole object, but all I want is the names:

IList<Tribble> tribbles = session.CreateCriteria(typeof(Tribble)).List<Tribble>();
IList<string> names = new List<string>();
foreach (Tribble t in tribbles) {
    names.Add(t.Name);
}

I would like to be able to specify additional criteria, so is it possible to just exclude certain columns from being retrieved?

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Kevin Albrecht
  • 6,974
  • 7
  • 44
  • 56

5 Answers5

25

Here is the solution I eventually ended up using:

ICriteria c = session.CreateCriteria(typeof(Tribble));
c.SetProjection(Projections.ProjectionList().Add(Projections.Property("Name")));
IList<string> names = c.List<string>();

I got this idea from this old StackOverflow question.

Community
  • 1
  • 1
Kevin Albrecht
  • 6,974
  • 7
  • 44
  • 56
7

Almost five years later..., this is what you could do using NHibernate.Linq:

IList<string> names = session.Query<Tribble>().Select(t => t.Name).ToList()
Steve
  • 50,173
  • 4
  • 32
  • 41
Ulf Åkerstedt
  • 3,086
  • 4
  • 26
  • 28
2

What about executing a query by string?

IList<string> names = session.CreateQuery("select name from Tribbles").List<string>();
Steve
  • 50,173
  • 4
  • 32
  • 41
Moskie
  • 1,277
  • 2
  • 16
  • 23
  • 1
    Technically, you actually would have to do this: IList names = session.CreateQuery("select t.name from Tribbles t").List(); – Kevin Albrecht Jul 02 '09 at 18:44
2

You can do something like this :

IQuery query = dao.GetQuery(@"SELECT u.Id
                                FROM UserImpl u
                               WHERE u.UserName = :username");
               query.SetParameter("username", username);
return (long)query.UniqueResult();
ahsteele
  • 26,243
  • 28
  • 134
  • 248
Shiva
  • 1,379
  • 1
  • 15
  • 32
-2

You typically don't. It rarely makes sense to have a partially populated business object.

Why would you want to do this?

Jamie Ide
  • 48,427
  • 16
  • 81
  • 117
  • I am using it throughout the entire program with dozens of classes, this is the only time I've needed to do this and it is necessary in this circumstance. – Kevin Albrecht Jul 02 '09 at 17:24
  • Can you explain further what the use case is? – Jamie Ide Jul 02 '09 at 18:50
  • Doesn't this happen all the time? For example, I want to display an Employee's details plus the name of its Office. I don't need the whole office, just the name. – cbp Sep 18 '09 at 04:23
  • @cbp: It does happen all the time. Assuming that Employee is mapped m:1 to Office, NHibernate will retrieve Office when the Employee is loaded using a join. When working with business objects you always return fully populated objects (there are exceptions, of course). That's just the way it is with object oriented programming. – Jamie Ide Sep 18 '09 at 16:19