Maintaining graph consistency with nHibernate

If I use bidirectional associations in nHibernate, do I need to add my own code on both sides of the relationship to automatically update the other side?

For example, if I have a many-to-one relationship between BookandCategory

public class Book{
    public Category Category{ get; set; }
}

public class Category{
    public IList Books{ get; set; }
}

Do I need to add code to Book.Category set () like this:

private Category _category;
public Category Category {
    get { return _category;  }
    set {
        Category priorCategory = _category;
        Category newCategory = value;

        if( newCategory != priorCategory ) {
            if( priorCategory != null ) {
                _category = null;
                priorCategory.Books.Remove( this );
            }

            _category = newCategory;
            if( newCategory != null ) {
                newCategory.Books.Add( this );
            }
        }
    }
}

and also add code to the .Books category something like this so that callers can add and remove books from Category.Books (e.g., Category.Books.Add()and Category.Books.Remove())?

(handling this, wrapping the List in an ObservableCollection so that I can respond to adding / removing 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;
}

// this just calls OnBookAdded() and OnBookRemoved() in response to 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 );
        }
    }
}

nHibernate - , ?

+3
1

, "" (.. , "" ). , , , , .

+2

Source: https://habr.com/ru/post/1728846/


All Articles