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?
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:
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).