Database Reference
In-Depth Information
12-4. Recalculating a Property Value When an Entity
Collection Changes
Problem
You want to recalculate a property value on the entity when its entity collection changes.
Solution
Both
EntityCollection
and
EntityReference
derive from
RelatedEnd
.
RelatedEnd
exposes an
AssociationChanged
event. This event is raised when the association is changed or modified. In particular, this event is raised when an
element is added to, or removed from, a collection.
To recalculate a property values, we implement a handler for the
AssociationChanged
event.
Let's say that you have a model with a shopping cart and items for the cart. The model is shown in Figure
12-4
.
Figure 12-4a.
A model for a cart
Figure 12-4b.
The cart's items
The code in Listing 12-4 demonstrates using the
AssociationChanged
event to recalculate the CartTotal property
on the Cart entity when items are added to, or removed from, the CartItems collection.