R – NHibernate self-join many-to-many symmetric relationship (person friends problem)

nhibernatenhibernate-mapping

Is there any way to set-up a symmetric self-join relationship mapping in NHibernate? Suppose we have two tables:

Users
  id

Relations
  id
  user1
  user2
  relation_type

The User and Relation classes should look like this:

class User
{
    public virtual int Id { get; set; }
    public virtual string Name { get; set; }
    public virtual ISet<Relation> Relations { get; set; }
}

class Relation
{
    public virtual int Id { get; set; }
    public virtual User User1 { get; set; }
    public virtual User User2 { get; set; }
    // Let's leave the RealationType as string for the sake of brevity 
    public virtual string RelationType { get; set; }
}

I do NOT want the relations table to have two rows for the same relation. But the relation MUST be symmetric, which means if there's a relation between two users, A and B, the Relations collection of the user A must contain a relation with user B and the relations of user B must contain a relation to A.

It sounds almost like a challenge. But, can someone solve this? Please, if you can, post the xml mapping. I'm not using Fluent.

Best Answer

You can use Key-Many-To-One mapping and remove the Id field from the relation entity. Also you better use inheritance for different relation types.