Note that there are some explanatory texts on larger screens.

plurals
  1. POAutomatically updating corresponding collection in NHibernate?
    primarykey
    data
    text
    <p>My database has two tables:</p> <pre><code>Users UserId PK Likes LikeId PK LikedUserId FK LikingUserId FK </code></pre> <p>These tables represent user 'likes'. Likes are directional - user A likes user B, but user B does not like user A.</p> <p>I am mapping with NHibernate like this:</p> <pre><code>&lt;class name="User" table="Users"&gt; &lt;id name="UserId"&gt; &lt;generator class="assigned"&gt;&lt;/generator&gt; &lt;/id&gt; &lt;idbag name="LikedBy" table="Likes" inverse="true"&gt; &lt;collection-id column="LikeId" type="guid"&gt; &lt;generator class="guid.comb"/&gt; &lt;/collection-id&gt; &lt;key column="LikedUserId"/&gt; &lt;many-to-many column="LikingUserId" class="User"/&gt; &lt;/idbag&gt; &lt;idbag name="Liking" table="Likes"&gt; &lt;collection-id column="LikeId" type="guid"&gt; &lt;generator class="guid.comb"/&gt; &lt;/collection-id&gt; &lt;key column="LikingUserId"/&gt; &lt;many-to-many column="LikedUserId" class="User"/&gt; &lt;/idbag&gt; &lt;/class&gt; </code></pre> <p>Corresponding to this class:</p> <pre><code>public class User { public Guid UserId { get; set; } public ICollection&lt;User&gt; LikedBy { get; set; } public ICollection&lt;User&gt; Liking { get; set; } } </code></pre> <p>This works fine. However, the <code>Liking</code> and <code>LikedBy</code> collections for two different users can get out of sync. For instance:</p> <pre><code>using (var session = new NHibHelp.OpenSession()) { var user1 = session.GetById&lt;User&gt;(id1); var user2 = session.GetById&lt;User&gt;(id2); int initialCount = user2.LikedBy.Count(); user1.Liking.Add(user2); session.Update(user1); int finalCount = user2.LikedBy.Count(); Assert.AreEqual(initalCount,finalCount); // passes } </code></pre> <p>So if I add to the <code>Liking</code> collection of one user, the <code>LikedBy</code> collection of another user is not updated. To have it updated, I need to do <code>Session.Refresh()</code>.</p> <p>This isn't ideal. I'm quite new to NHibernate, so I don't know if there is another solution - is there anything better I can do? For instance, is it possible to map this scenario in such a way that <code>LikedBy</code> is automatically updated when appropriate?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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