I am wondering since nhibernate has to make the entire object does it make sense to do this?
Session.Query<Table>().Where(x => x.Id == id).Select(x => x.ColumnA).FirstOrDefault();
or would it be better to do this
Session.Query<Table>().Where(x => x.Id == id).FirstOrDefault();
I am trying to decide if I should make a separate method in my service layer to just return back ColumnA and have another method that returns all the fields back.
Or should I just have the one method that return all the fields like the second example would.
On one hand if I do it the first way then less data has to come back from the database especially when you know only one column will be used. On the other hand though it would suck if I need to it for each column.
Session.Query<Table>().Where(x => x.Id == id).Select(x => x.ColumnB).FirstOrDefault();
Session.Query<Table>().Where(x => x.Id == id).Select(x => x.ColumnC).FirstOrDefault();
Selecting 1 property (or a number of them) is a projection. NHibernate definitely does support projections, and there are many situations in which it makes sense to use a projection.
It depends on what problem you are trying to solve. If you do not know that there is a problem, then I would very much suggest not using projections to select single properties – it is much easier to work with the entities. However if you are facing a real performance issue, then you should analyze what’s happening and where the bottleneck is, and if after that analysis you discover that it really is because you’re selecting the whole entity instead of a single property of it, then by all means use a projection.
Having said that, unless your entities have lots of properties and/or large data, it probably won’t make sense to project a single property. Also there will be some minor performance penalties such as duplicate query plans.