title: Nhibernate mapping - User and Friends
body: <p>I am trying a social network type scenario using Nhibernate as my ORM.</p>
  
  <p>I have a User table and a Friend table.</p>
  
  <pre><code>User Table
  ----------
  UserID
  FirstName
  LastName
  Email
  
  Friend Table
  -------------
  UserID
  FriendUserID
  AddedDateTime
  </code></pre>
  
  <p>This means the in the Friend Table it could have many to many records like</p>
  
  <pre><code>A - B (A initiated a friend request to B, accepted)
  A - C (A initiated a friend request to C, accepted)
  B - C
  D - A (D initiated a friend request to A, accepted)
  B - E
  </code></pre>
  
  <p>How can I have a Nhibernate property such that if I call userObject.Friends for A, I get back B,C and D as user objects.</p>
  
  <p>Mapping xml for User Object...</p>
  
  <pre><code>&lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"&gt;
    &lt;class name="Namespace.Data.Entities.User,Namespace.Data.Entities" table="`User`" lazy="true"&gt;
      &lt;id name="UserId" column="`UserId`" type="Guid"&gt;
        &lt;generator class="assigned" /&gt;
      &lt;/id&gt;
      &lt;property type="string" length="150" name="FirstName" column="`FirstName`" /&gt;
      &lt;property type="string" length="150" name="LastName" column="`LastName`" /&gt;
      &lt;property type="string" not-null="true" length="256" name="Email" column="`Email`" /&gt;    
      &lt;bag name="UsersFriends" inverse="true" lazy="true" cascade="all"&gt;
        &lt;key column="`UserID`" /&gt;
        &lt;one-to-many class="Namespace.Data.Entities.Friend,Namespace.Data.Entities" /&gt;
      &lt;/bag&gt;
      &lt;bag name="FriendsofUser" inverse="true" lazy="true" cascade="all"&gt;
        &lt;key column="`FriendUserID`" /&gt;
        &lt;one-to-many class="Namespace.Data.Entities.Friend,Namespace.Data.Entities" /&gt;
      &lt;/bag&gt;
    &lt;/class&gt;
  &lt;/hibernate-mapping&gt;
  </code></pre>
  
  <p>and Friend object...</p>
  
  <pre><code>&lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"&gt;
    &lt;class name="Namespace.Data.Entities.Friend,Namespace.Data.Entities" table="`Friend`" lazy="true"&gt;
      &lt;id name="Id" column="`ID`" type="int"&gt;
        &lt;generator class="native" /&gt;
      &lt;/id&gt;
      &lt;property type="DateTime" not-null="true" name="AddedDateTime" column="`AddedDateTime`" /&gt;
      &lt;many-to-one name="User" cascade="none" column="`UserID`" not-null="true" /&gt;
      &lt;many-to-one name="FriendUser" cascade="none" column="`FriendUserID`" not-null="true" /&gt;
    &lt;/class&gt;
  &lt;/hibernate-mapping&gt;
  </code></pre>