Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bidirectional one-to-many associations with indexed collections in NHibernate

Tags:

nhibernate

Last summer, I asked a question regarding how to add new object to an IList mapped as a one-to-many with NHibernate. One of the answers let me to this paragraph in the documentation:

Please note that NHibernate does not support bidirectional one-to-many associations with an indexed collection (list, map or array) as the "many" end, you have to use a set or bag mapping.

While I am pretty sure I understand what this paragraph says, I have no idea why or how to work around this limitation. As I am now again working with a model that seems to require a "bidirectional one-to-many association with an index collection", I figured the time was right for follow-up questions:

  1. Why does NHibernate have this limitation on associations? It is my impression that the guys behind NHibernate are quite clever, so I assume there is a pretty good reason.

  2. What are the common workarounds for this shortcoming? Making the collection a non-indexed bag and adding an explicit Position property to the child class? Any better solutions?

like image 975
Jørn Schou-Rode Avatar asked Apr 15 '10 08:04

Jørn Schou-Rode


1 Answers

This was asked 4 months ago, so I don't know if you're still interested :-)

The conceptual reason for not supporting bidirectional indexed associations is simple: the index only makes sense in one direction.

For example, consider an Invoice class with a Lines property of type IList<Line>.

Setting line.Invoice = anInvoice makes no sense, as it's impossible to determine what the list index should be.

Keep in mind that NHibernate "sees" bidirectional relationships as two different relationships (hence the need for inverse="true" on the side not in charge of maintaining it)

The workaround is exactly what you suggested: a Position/Index/etc property in the child class.

like image 112
Diego Mijelshon Avatar answered Sep 29 '22 03:09

Diego Mijelshon