Sunday, April 17, 2011

Linq To Sql - Update a value when another value changes

With Linq To Sql - what is the best way to update the value of one table in a database when a value changes in a different table?

For example in TableA, there is a column called DateModified. TableA has an association to TableB. Now I want to set the value of the DateModified field to the current date every time the record changes in tableA AND everytime a child record is created/updated/deleted in TableB.

How can this be achieved?

From stackoverflow
  • If the change was just in the one record, you can use either the On*Changed partial methods, or you can override SubmitChanges on the data-context, call GetChangeSet, and apply the changes just before they are updated. The latter (data-context) approach is useful for catching a broad spectrum of changes, where-as the On*Changed approach is useful for logic specific to individual properties.

    However, in the case presented (non-homogeneous updates), I expect a database trigger may be more appropriate.

    tvanfosson : If it's being updated on every change I'd rather not implement the On*Changed method for every property, but register a PropertyChanged handler since each setter is going to fire SendPropertyChanged for that column if it is successful.
    tvanfosson : BTW -- I agree that the trigger is a better way to handle this.
  • Either do Insert/Update/Deletes on TableB via a StoredProcedure which allows you to perform the update on TableA or have Insert/Update/Delete triggers on TableB which updates TableA

    I wouldn't try to accomplish this in LINQ as it will involve either overriding various IDE-generated code structures (maintenance nightmare) or extra calls to the Database to get the related TableA item.

  • You could register a PropertyChanged event handler on the child entity in OnCreated (implemented in a partial class) and have that handler update the parent property. If you don't care about the already loaded classes getting the change, using a DB trigger as @Marc suggests would also be an option.

    EDIT: If you need to catch deletes as well, you can implement the delete partial method for the data context to call the same handler method to update the parent of the entity being deleted.

0 comments:

Post a Comment