How can I effectively update the parent EntityObject property which is there to expose only the sum of the related child entity collection property? I need an update in parent any time there is a change of property value in any of the child entity.
An example: I have a parent EntityObject "Company" and a collection of related child objects "Employee". These have association in EF between each other (one Company to collection of Employees). In Employee partial class I have added a custom calculated property "Salary" and in a Company partial class I have added a custom property "TotalSalaries".
Now, if any Employee Salary property is updated to a new value, I want to immediately update the Company object property TotalSalaries value.
Whenever the Employee property changes and if then I always run a full query inside the Company object like:
TotalSalaries = Me.Employees.Sum(Function(x) x.Salary)
...that looks like a highly inefficient thing to do, especially if all custom property values in Employee class are changed by looping for example (the above query is run over and over again).
Can the property update be reflected in the parent class more efficiently?
I figured this out. On the Employee class, I can capture the original property value in a class-level PropertyChanging event:
Private Sub employee_PropertyChanging(ByVal sender As Object, ByVal e As PropertyChangingEventArgs) Handles Me.PropertyChanging
Dim propBeignChanged As String = e.PropertyName
If propBeignChanged = "Salary" Then
OriginalValue = CType(sender, Employee).Salary 'store the current value temporarily to a variable
End If
End Sub
And then I can get the new value either in a class-level PropertyChanged event or the property-specific On[Property]Changed event, calculate the difference against the temporarily stored original value and pass the difference to the parent object.
Private Sub OnSalaryChanged()
Dim diff as Double = Me.Salary - OriginalValue
'and finally pass diff to the parent object for updating its total...
End Sub
I believe this must be a much faster approach than querying the whole EntityCollection.