NHibernate Many-to-Many Mapping not working

Posted by ClutchDude on Stack Overflow See other posts from Stack Overflow or by ClutchDude
Published on 2010-12-23T04:45:51Z Indexed on 2010/12/23 4:54 UTC
Read the original article Hit count: 230

Filed under:
|
|
|

I have a Nhibernate mapping file for a simple user/role mapping.

Here are the mapping files:

Users.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Sample.Persistence" namespace="Sample.Persistence.Model">
    <class name="User" table="Users">
        <id name="UserKey">
            <generator class="identity"/>
        </id>

        <property name="UserName" column="UserName" type="String" />
        <property name="Password" column="Password" type="Byte[]" />

        <property name="FirstName" column="FirstName" type="String" />
        <property name="LastName" column="LastName" type="String" />
        <property name="Email" column="Email" type="String" />

        <property name="Active" column="Active" type="Boolean" />
        <property name="Locked" column="Locked" type="Boolean" />

        <property name="LoginFailures" column="LoginFailures" type="int" />
        <property name="LockoutDate" column="LockoutDate" type="DateTime" generated="insert" />

        <property name="Expired" column="Expired" type="Boolean" generated="insert"/>

        <set name="Roles" table="UsersRolesBridge"   lazy="false">
            <key column="UserKey" />
            <many-to-many class="Role"
            not-found="exception"
            column="RoleKey" />
        </set>

    </class>
</hibernate-mapping>

Role.hbm.xml

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Sample.Persistence" namespace="Sample.Persistence.Model">
    <class name="Role" table="Roles">
        <id name="RoleKey">
            <generator class="identity"/>
        </id>
        <property name="Name" column="Name" type="String" />

        <set name="Users" inverse="true" atable="UsersRolesBridge" lazy="false" >
            <key column="RoleKey" />
            <many-to-many class="User" column="UserKey" />
        </set>
    </class>
</hibernate-mapping>

I am able to retrieve roles for each user via NHibernate but when I go to save a new object, the roles are not saved in the Bridge table.

The user is created and insert with no issues. I've checked that the Role collection, a field on the user, is being populated with the proper rolekey before the Session.Save() is called.

There is no exception thrown as well.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET