hibernate - Maintaining graph consistency in relationships with nHibernate -


if use bidirectional associations in nhibernate, necessary me add own code both sides of relationship automatically update other side?

for example, if have many-to-one relationship between book , category

public class book{     public category category{ get; set; } }  public class category{     public ilist books{ get; set; } } 

do need add code book.category's set() this:

private category _category; public category category {     { return _category;  }     set {         category priorcategory = _category;         category newcategory = value;          if( newcategory != priorcategory ) {             if( priorcategory != null ) {                 _category = null;                 priorcategory.books.remove( );             }              _category = newcategory;             if( newcategory != null ) {                 newcategory.books.add( );             }         }     } } 

and also add code category.books callers can add , remove books category.books (e.g., category.books.add() , category.books.remove())?

(handling wrapping list in observablecollection can respond add/remove events)

private ilist _books { get; set; } public icollection<book> books {     get{         if( _books == null ) _books = new arraylist( );         var observablebooks = new observablecollection<book>( _books.cast<book>( ) );         observablebooks.collectionchanged += bookcollectionchanged;         return observablebooks;     } }  private void onbookadded( book addedbook ) {     _books.add( addedbook );     addedbook.category = this; }  private void onbookremoved( book removedbook ) {     _books.remove( removedbook );     removedbook.category = null; }  // calls onbookadded() , onbookremoved() in response change events private void bookcollectionchanged( object sender, notifycollectionchangedeventargs e ) {     if( notifycollectionchangedaction.add == e.action ) {         foreach( book addedbook in e.newitems ) {             onbookadded( addedbook );         }     }      if( notifycollectionchangedaction.remove == e.action ) {         foreach( book removedbook in e.olditems ) {             onbookremoved( removedbook );         }     } } 

or nhibernate graph consistency automatically update of you?

not necessary update both sides, necessary update "master" direction of relationship (i.e. 1 not mapped "inverse"). best practice write code keep 2 directions in synch, , find makes life easier in long run.


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -

unicode - Are email addresses allowed to contain non-alphanumeric characters? -