Nhibernate - Map List Does Not Update List Indexes

I have one class of self-regulation. The child has a link to the parent, and the parent has a list of children. Since the list of children is ordered, I am trying to match the relation using NHibernate.

This is my mapping:

<class name="MyClass"> <id name="Id"> <generator class="native"/> </id> <list name="Children" cascade="delete" inverse="true"> <key column="ParentId"/> <index column="ListOrder"/> <one-to-many class="MyClass"/> </list> <many-to-one name="Parent" class="MyClass" column="ParentId"/> </class> 

The problem I'm running into is when I have a child ↔ parent bi-directional display, the list index (ListOrder) is not updated in the database when I do my CRUD dance. This means that when I, for example, delete a child, I get holes in the list of children after saving to the database and selecting the parent. If I remove bidirectionality without having many-to-one from the children of the parent element (and not the opposite = true), the ListOrder will be updated correctly.

Have any of you seen this before? Is there a simple solution?

+6
mapping orm nhibernate- nhibernate-mapping
source share
1 answer

Yes, this is due to inverse = true, an alternative solution would be to use a kit or bag instead of a list with order = "ListOrder", add a ListOrder column as a property of the MyClass class with an empty setter and getter, which always returns the index from the parent collection. Like this:

 <class name="MyClass"> <id name="Id"> <generator class="native"/> </id> <bag name="Children" cascade="delete" inverse="true" order-by="ListOrder"> <key column="ParentId"/> <one-to-many class="MyClass"/> </bag> <property name="ListOrder" column="ListOrder"/> <many-to-one name="Parent" class="MyClass" column="ParentId"/> </class> 

and class

 public class MyClass { public virtual int ID { get; set; } public virtual IList<MyClass> Children { get; set; } public virtual MyClass Parent { get; set; } public virtual int ListOrder { get { if (Parent == null || !Parent.Children.Contains(this)) return -1; return Parent.Children.IndexOf(this); } set { } } } 
+5
source share

All Articles