Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a list collection in NHibernate with a non-nullable index?

I'm using FluentNHibernate to map a bi-directional one-to-many relationship where ordering is important, so I'm using a list:

        HasMany(x => x.Children)
            .AsList(index => index.Column("CHILD_INDEX"))
            .KeyColumn("PARENT_ID")
            .Not.LazyLoad()
            .Access.CamelCaseField()
            .Cascade.AllDeleteOrphan();

On the other side, it's mapped like this:

        References(x => x.Parent)
            .Column("PARENT_ID")
            .Not.Nullable()
            .Fetch.Join()
            .Not.LazyLoad()
            .Cascade.SaveUpdate();

Now in my actual database, the CHILD_INDEX column is not nullable. However, when NHibernate persists the child elements during an insert, it doesn't insert the CHILD_INDEX column. It then performs an UPDATE to set the CHILD_INDEX. This is odd to me, as it certainly has the index value when it does the insert.

Is there a way to tell NHibernate to write the index column during the insert?

like image 493
Scott Whitlock Avatar asked Oct 11 '22 16:10

Scott Whitlock


1 Answers

Bidirectional indexed collections (i.e. lists and dictionaries) are not supported.

Since they are required to avoid inserting null and then updating (see the note in 6.4. One-To-Many Associations), the workaround is to use a bag instead of a list and create a regular index property in the many side.

You can then wrap the collection manipulation to deal with both sides' references and indexes.

like image 112
Diego Mijelshon Avatar answered Nov 15 '22 09:11

Diego Mijelshon