Notifying the "one" object about changes to the "many" objects in one-to-many relationships? RRS feed

  • Question

  • For objects created in the O/R Designer that participate in a one-to-many relationship, how can the object on the "one" side of the relationship be notified of changes (additions, deletions, and updates) to its associated objects on the "many" side of the relationship?


    For example, I extended an Order object with a property, Order.OrderAmount, that is a sum of (Quantity * UnitPrice) for all of Order.OrderLineItems.


    To keep the OrderAmount synchronized in data binding scenarios where the user is changing OrderLineItems, the Order object needs to know when its OrderLineItems are added, removed, or updated so that it can send a property changed notification for OrderAmount.


    It seemed like the O/R Designer should have provided extension methods for OrderLineItemsChanging/OrderLineItemsChanged like it did for all of the other (non-collection) properties of Order, but they were nowhere to be found. Therefore, to get what I wanted, I:

    • Implemented the partial Order.OnCreated function, in which I provided a delegate for EntitySet.ListChanged, which gets called when OrderLineItems are added or removed (but not updated).
    • Have the OrderLineItem object call a custom method, Order.SendSubtotalChanged, on its associated Order object when OrderLineItem.Quantity or .UnitPrice is updated.

    My solution seems to work fine and fits my needs, but I have the feeling that this is not the "intended" way to do this, and that I am missing a more elegant solution.

    Wednesday, October 22, 2008 2:55 AM


  • You might be able to refine the approach a little by listening to INotifiyPropertyChanged events.  E..g order can subscribe to changes in its OrderLineItems without you having to actually add any logic to the OrderLineItem itself.  There might be more house-keeping with this approach tho - e.g. making sure that the order unsubsribes from any orderLine which is removed from the order.


    So, all in all I'm not sure whether the INotifyPropertyChanged approach is any better than what you have done. 


    No other options are coming to mind as I write this...




    Friday, October 24, 2008 9:18 PM