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:
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.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With