LINQ Timestamp - Automatically updating a 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 which needs to be updated anytime the object is changed.
We can come up with several "dirty" solutions for solving this, but not sure we are going down the right route.
Is there an easy way(possibly, in a LINQ Object partial,DataContext,etc) to be able to say,If you INSERT/UPDATE, always set "Last Update" column to DateTime.Now?
Update We have operations on this table in thousands of locations in our application, and therefor we are trying to find a way to let LINQ accomplish this for us, without having to find开发者_Go百科 every location this object is updated.
You could create a trigger which automatically updates this info anytime the table data is touched for insert/update.
You can extend your DataContext and override the Update methods, see here:
http://msdn.microsoft.com/en-us/library/bb425822.aspx#linqtosql_topic21
Make sure you call the base
version of whatever methods you override after setting the Last Update time.
Assuming you're talking 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 "set LastUpdate property" isn't necessarily trivial. One way you could do it that I came up with in a few seconds is to create an interface that has the LastUpdate property, and then derive 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 in the bit above with
(insert as IHasLastUpdate).LastUpdate = DateTime.Now;
I'd stick with triggers or modifying the datacontext primarily, but you could also try the following if you're on EF::
Create partial classes for all of the types that you want to do this for and then create a constructor in these which adds an eventhandler to the propertychanged event and updates the timestamp whenever something is changed.
精彩评论