Tuesday, June 21, 2011

NHibernate and select one column only

You can make use of Projections when it comes to selecting from specific columns. For example sometime you may need to select values only from Id column instead of loading complete matching rows.

Lets quickly take a look at an example. Suppose we have a table called Customer with columns Id, FirstName, LastName, Street, City, PostalCode, Country. Now when doing our query we only want to select all Ids less then value 10. We can accomplish this by doing something like this

IList<int> customerIds = session.CreateCriteria<Customer>()
                .Add(Restrictions.Lt("Id", 10))
                .SetProjection(Projections.Property("Id"))
                .List<int>();

No comments: