views:

229

answers:

2

I've got a simple routine that populates a record in a table. I have fields that I only want to update if an actual change has taken place. The function could get called even if the user did not change anything. Is there an easy way to tell if changes have taken place? Here's the function:

Sub Edit(ByVal key as Integer, ByVal myval1 As Integer?, ByVal myval2 As Integer?)

    Dim db As New MyDatabaseDataContext

    Dim form = (From x In db.MyTables Where x.id = key).SingleOrDefault

    form.field1 = myval1
    form.field2 = myval2

    If [???] Then
        form.mod_date = Now
    End If

    db.SubmitChanges()

End Function

This is a little simplified - I'd rather not check each relationship between field1 and myval1, field2 and myval2, etc., because there could be many fields, and you have to take Nothing into account for each one, blah blah blah. Is there any way to just ask "form" if the assignments actually changed anything? I know behind the scenes it won't do a database update if nothing has changed, but is that exposed to me before I commit the change?

A: 

It looks like you simply want to set a modification date, but only if there are changes. The way I've handled this is to use a partial class implementation and register a PropertyChanged event handler in the OnCreated partial method, which gets called in the default constructor in the designer code. In the property changed handler, I update the modification data field (if that's not the property being updated, of course). Note that I set the backing field directly as well so that the event doesn't get refired due to my change.

Example (sorry for the C#, but that's what my code is implemented in).

partial void OnCreated()
{
    this.PropertyChanged += new PropertyChangedEventHandler( Participant_PropertyChanged );
}

void Participant_PropertyChanged( object sender, PropertyChangedEventArgs e )
{
    if (e.PropertyName != "mod_date")
    {
        this._mod_date = DateTime.Now;
    }
}
tvanfosson
+2  A: 

You can take care of that kind of thing on the DataContext itself.

For example, you can use the UpdateXXX methods to catch changes to objects and record your date.

So to relate to your example (assuming you have a class named MyTable), on your DataContext:

Private Sub UpdateMyTable(ByVal instance As MyTable)
    instance.mod_date = Now
    Me.ExecuteDynamicUpdate(instance)
End Sub

As far as I can tell, the DataContext will detect if changes have taken place and only call that method for actual updates (but I could be wrong on this one, I'll check).

Denis Troller