many-to-many with extra columns nhibernate

So I have two tables Users and Groups. These tables are (in the database) liked with a UGlink link table. Now except for the primary-foreign keys the link table have an extra column: Date.

From what I understand this means that I have to have two Many-to-One, with the link "in the middle".

However since I'm almost never is interested of the extra column value, is there anyway to avoid the link? That is I want to be able to write:

thisUser.Groups

to get the groups, instead of:

thisUser.UGlinks.Group

enter image description here


Solution 1:

The many-to-many, without the explicit mapping of the pairing table as an entity - is in NHibernate of course suported. So, in case, that the Date column is autogenerated, or nullable (does not have to be inserted by app/NHiberante), we can do it like here: 6.8. Bidirectional Associations

<class name="User">
    <id name="Id" column="Uid"/>
    ...
    <bag name="Groups" table="UGlink" lazy="true">
        <key column="Uid"/>
        <many-to-many class="Group" column="Gid"/>
    </bag>
</class>

<class name="Group">
    <id name="id" column="Gid"/>
    ...

    <!-- inverse end -->
    <bag name="Users" table="UGlink" inverse="true" lazy="true">
        <key column="Gid"/>
        <many-to-many class="User" column="Uid"/>
    </bag>
</class>

So, what we have is a mapping, in which NHiberante does care about the pairing table, and we can do:

thisUser.Groups

But if I could suggest, do not go with many-to-many. The many-to-one with pairing object is (I'd say) better solution, because it will support searching Users by Groups and vice versa.

See Chapter 24. Best Practices, cite:

Don't use exotic association mappings.

Good usecases for a real many-to-many associations are rare. Most of the time you need additional information stored in the "link table". In this case, it is much better to use two one-to-many associations to an intermediate link class. In fact, we think that most associations are one-to-many and many-to-one, you should be careful when using any other association style and ask yourself if it is really neccessary.

Here is some more detailed explanation how to do it without many-to-many: Nhibernate: How to represent Many-To-Many relationships with One-to-Many relationships?