R – NHibernate: restore inner objects’ events

nhibernate

Suppose I have

public class Parent
{
   private IList<Child> _children;
   public void AddChild(Child child)
   {
      _children.Add(child);
      child.OnSmthChanged += ParentSmthChangedHandler;
   }
   public void RemoveChild(Child child)
   {
      _children.Remove(child);
      child.OnSmthChanged -= ParentSmthChangedHandler;
   }
}
public class Child
{
   public event EventHandler OnSmthChanged;
}

How do I make NHibernate to restore events when _children are loaded from database? Notice that:

  • I don't want Parent bi-directional reference in Child
  • _children is a field so I cannot intercept its "set"
  • I don't like to use global events like OrderEvents.OrderChanged(order)

So, I think about intercepting NHibernate doing load of _children and there recursively add events. Two questions:

  1. How do I do this interception for _children loading? Intercepting all collections loading would be too ineffective I guess. Small note: I use Fluent NHibernate so specific advice would be nice.
    • Something like OnAfterObjectCreated(Parent) would not work because I will not have access to the private field. Well, I can use reflection to setup if this is the only way.
  2. Is there a better way?

Best Answer

You can tell nhibernate to use observable collection for _children field:

<bag collection-type="uNhAddIns.WPF.Collections.Types.ObservableBagType`1[Your.Namespace.Child
, Your.Assembly.Name], uNhAddIns.WPF" ... />

then:

public Parent()
{
   (_children as INotifyCollectionChanged).CollectionChanged += DoSomething;
}

public void DoSomething(object sender, NotifyCollectionChangedEventArgs e)
{
    if(e.Action == NotifyCollectionChangedAction.Add)
        foreach(var child in e.NewItems.Cast<Child>())
           child.OnSmthChanged += ParentSmthChangedHandler;

    if(e.Action == NotifyCollectionChangedAction.Remove)
        foreach(var child in e.OldItems.Cast<Child>())
           child.OnSmthChanged -= ParentSmthChangedHandler;
}

uNhAddins you can find here.

Related Topic