If we query objects with lot of dependencies NHibernate can (and I believe by default will) load all of them. In many situations this is not necessary. For example all we want is to count objects with some properties or show only 3 properties of some object. The object has lets say 20 properties, some of them pointing to other DB objects and those pointing to another objects. How to optimize this? It is actually quite easy. Use Linq’s SELECT method. NHibernate is clever enough to translate it into optimized SQL. But there is one drawback to consider: NHibernate can not optimize queries where the ‘where condition’ is passed as a variable.
Example code:
//Optimize query so that it reads only certain columns Repository.Query<MyObject>().Where(mo => mo.SomeProperty == true //or whatever other condition ).Select(mo => new { mo.Id, mo.Name }); //query optimalization - read only Id and Name;