在与nHibernate的关系中保持图形一致性

时间:2010-01-17 20:55:15

标签: nhibernate hibernate

如果我在nHibernate中使用双向关联,我是否有必要将自己的代码添加到关系的双方以自动更新另一方?

例如,如果我在BookCategory之间存在多对一关系

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

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

我是否需要将代码添加到Book.Category的set()中,如下所示:

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 );
            }
        }
    }
}

将类似的内容添加到Category.Books中,以便调用者可以在Category.Books中添加和删除书籍(例如Category.Books.Add()Category.Books.Remove())?< / p>

(通过将List包装在ObservableCollection中来处理它,以便我可以响应添加/删除事件)

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是否会为您执行任何图形一致性,它会为您自动更新其中一些内容?

1 个答案:

答案 0 :(得分:2)

不必更新双方,但始终需要更新关系的“主”方向(即未映射为“反向”的方向)。因此,最佳做法是编写代码以使两个方向保持同步,并且您会发现它使您的生活从长远来看更容易。