LINQ Timestamp - auto update timestamp column?

I am not sure if there is a quick way to solve this problem.

We have LINQ objects / tables that have a Last Update column that needs to be updated at any time when the object has been modified.

We can come up with some "dirty" solutions to solve this issue, but are not sure that we are going on the right route.

Is there a simple way (perhaps in a partial LINQ object, DataContext, etc.) to be able to say: If you are INSERT / UPDATE, always set the Last Updated column in DateTime.Now ?

Update We have operations in this table in thousands of places in our application, and therefore we are trying to find a way for LINQ to do this for us, without having to find every location of this object being updated.

+4
source share
4 answers

You can create a trigger that automatically updates this information at any time when the table data is affected for insert / update.

+4
source

You can expand your DataContext and override update methods, see here:

http://msdn.microsoft.com/en-us/library/bb425822.aspx#linqtosql_topic21

Make sure you call the base version of all the methods that you redefined after setting the last update time.

+4
source

Assuming you say LINQ to SQL, you can override SubmitChanges and therefore basically do whatever you want ... for example:

 partial class YourDataContext { public override void SubmitChanges(ConflictMode failureMode) // don't worry, the parameterless version you know calls this one... { var changeSet = GetChangeSet(); foreach (object insert in changeSet.Inserts) { // set LastUpdate property } foreach (object update in changeSet.Updates) { // set LastUpdate property } base.SubmitChanges(); } } 

Of course, the commented “LastUpdate property” is not necessarily trivial. One way to do this in a few seconds is to create an interface that has the LastUpdate property and then extract all your linq objects from it:

 public interface IHasLastUpdate { DateTime LastUpdate { get; set; } } partial class Order : IHasLastUpdate {} partial class Product : IHasLastUpdate {} // etc 

Then you could replace the commented lines with the bit above with

 (insert as IHasLastUpdate).LastUpdate = DateTime.Now; 
+2
source

I would like to use triggers or modify the datacontext in the first place, but you can also try the following if you are on EF:

Create partial classes for all types for which you want to do this, and then create a constructor in them that adds an event handler to the propertychanged event and updates the timestamp whenever something changes.

0
source

All Articles