开发者

How to add relationships (nhibernate)

Why do I need to add relationships for child and parent?

Child child = Session.Get(1);
Parent parent = Session.Load(1);
parent.Children.Add(child);
child.Parent = parent;

It works perfectly without parent.Children.Add(child) if use inverse=true and I don't need Children collection in c开发者_运维技巧urrent session (session per web request). Do you always add relationship for child and parent?


Setting child.Parent = parent is enough to persist the relationship.

However, if you don't add the child to the collection, you won't be able to take advantage of cascading, so you'll have to persist the child explicitly.

Also, if you don't set one of the sides, you'll have an inconsistent memory model (because the child won't be added to the collection unless you reload it).


I hope I understood you correctly.

class Parent { List Children {get;set;} class Child { Parent Parent {get;set;}

ANS1. In this scenario Inverse tells the nhibernate framework to leave the control mechanism of [Parent-Child] relationship to the Child (it is mostly about which object is responsible for Deleting/Updating the Child). With Inverse attribute on Children property Child is responsible for itself, otherwise Parent is responsible for deleting a Child.

ANS2. You do not need both properties (Children, Parent) in most cases (you need them if you specify inverse=true on Children). It only depends on the functionality you want to get.

Does this briefly answer your question?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜