开发者

Bidirectional one-to-many associations with indexed collections in 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜