Note that there are some explanatory texts on larger screens.

plurals
  1. POYet another many-to-many NHibernate question
    text
    copied!<p>Trying to implement relatively simple relationship between <code>User</code> and <code>Role</code>. <code>User</code> can be in many roles, same <code>Role</code> can belong to any number of <code>User</code>s. <code>Role</code>s are shared, i.e. all <em>admin</em> <code>User</code>s refer to the very same instance of class <code>Role</code>.</p> <p><code>User</code> mapping:</p> <pre><code> &lt;class name="User" lazy="false" table="Users"&gt; &lt;id name="Id" type="int"&gt; &lt;generator class="native"/&gt; &lt;/id&gt; &lt;property name="Name" column="Username" /&gt; &lt;bag name="RoleList" table="User_Role" inverse="true" lazy="false" cascade="save-update"&gt; &lt;key column="UserId" foreign-key="Id"/&gt; &lt;many-to-many class="Role" column="RoleId"/&gt; &lt;/bag&gt; &lt;/class&gt; </code></pre> <p><code>Role</code> mapping:</p> <pre><code> &lt;class name="Role" lazy="false" table="Roles"&gt; &lt;id name="Id" type="int"&gt; &lt;generator class="native"/&gt; &lt;/id&gt; &lt;property name="Name" column="Rolename"/&gt; &lt;property name="Description"/&gt; &lt;/class&gt; </code></pre> <p>There are three DB tables: one for <code>User</code>s, one for <code>Role</code>s and the third is for the many-to-many relation (with two foreign keys: <code>UserId</code> and <code>RoleId</code>). A primary key is the composite key of those two.</p> <p>The problematic <em>scenario</em>: the roles are predefined. In my C# code I am constructing a <em>user</em>, while attaching the <em>role</em> to it. The role is an object that was successfully fetched from DB with correct <em>id</em>. I am trying to save that <em>user</em> in the database.</p> <p>Now to the <strong>question</strong>: I am receiving a <em>duplicate key</em> DB error, since NHibernate is trying to insert the <code>Role</code> object into the appropriate table. Since the <code>RoleId</code> already belongs to the existing <em>role</em>, I would expect that no new role will be inserted in DB.</p> <p><em>Gory details</em>: I've also tried to debug the NHibernate and seen that for some reason <code>EntityIdentityInsertAction</code> receives a <code>Role</code> and calls base constructor. In the call to the base constructor the <code>Id</code> parameter is a simple hard-coded <em>null</em>. The stack trace also contains a call to <code>SaveWithGeneratedId()</code> (somewhere earlier in the chain), which implies that the <code>Id</code> for the existing <code>Role</code> object is not counted for some reason.</p> <p>This is all the info I've succeeded to find so far. Please tell what am I doing wrong.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload