Note that there are some explanatory texts on larger screens.

plurals
  1. POCorrect way to reordering items in a list (nhibernate)
    primarykey
    data
    text
    <p>What is the correct way to reorder a list when using NHibernate?</p> <p>This is my list:</p> <pre><code> private IList&lt;MediaItem&gt; media = new List&lt;MediaItem&gt;(); public virtual IList&lt;MediaItem&gt; Media { get { return media.ToReadOnlyCollection(); } } </code></pre> <p>And I'm reordering by passing an ordered list of <code>MediaItem</code> ids (<code>Guid</code>):</p> <pre><code> public virtual void UpdateMediaOrder(IList&lt;Guid&gt; mediaIds) { // TODO remove any unmatched items foreach (var mi in Media) { int index = mediaIds.IndexOf(mi.Id); if (index == -1) index = media.Count() -1; media[index] = mi; } } </code></pre> <p>When I reorder the list (in this case a list containing 3 items), NHibernate executes the following:</p> <pre><code>NHibernate: DELETE FROM PortfolioProjectMedia... NHibernate: INSERT INTO PortfolioProjectMedia... NHibernate: INSERT INTO PortfolioProjectMedia... NHibernate: INSERT INTO PortfolioProjectMedia... </code></pre> <p>I guess I expected to see <code>Updates</code> rather than clearing the list. </p> <p>Am I doing something wrong, or is this the intended behaviour?</p> <h3>Update</h3> <p>In case it wasn't already clear, I need to map my list as a NHibernate List (not a Set or a Bag) so that the index of the items is persisted.</p> <p>Here's the mapping of the <code>MediaItem</code> collection on <code>Project</code>. <code>MediaItem</code> has no reference to projects. The relationship is many-to-many.</p> <pre><code> HasManyToMany(p =&gt; p.Media) .Table("PortfolioProjectMedia") .Access.CamelCaseField() .ParentKeyColumn("ProjectId") .ChildKeyColumn("MediaItemId") .Cascade.SaveUpdate() .AsList(i =&gt; i.Column("ListIndex").Type&lt;int&gt;()); </code></pre>
    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.
 

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