The reason NHibernate issues a SELECT statement when trying to access the Friends collection, because it was not initialized when the user object was loaded. You can force the assembly to load either with the following request:
User user = session .CreateCriteria(typeof(User)) .SetFetchMode("Friends", FetchMode.Eager) .Add(Expression.IdEq(1)) .UniqueResult<User>();
or by adding fetch = "join" to your mapping file:
<?xml version="1.0" encoding="utf-8" ?> <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="Test" assembly="test"> <class name="User" table="Users"> <id name="Id" column="id"> <generator class="native"/> </id> <property name="Name" column="name"/> <set name="Friends" table="Friends" fetch="join"> <key column="user_id"/> <many-to-many class="User" column="friend_id"/> </set> </class> </hibernate-mapping>
It should be noted that there is a difference between UniqueResult and session.Load. If the user is not found in the database, you will get an ObjectNotFoundException with the second approach, while UniqueResult will return null. You can use any approach based on your needs.
source share