views:

288

answers:

3

In database, I have a LastEditTime column of type datetime. I used this to track last row update/insert time. Linq throws exception claiming that it can not insert null at that column.

Naturally, since LastEditTime column is NOT NULL, an exception is expected. My hand generated query inserts getutcdate(). How can I ask Linq to do similar?

+1  A: 

Create a partial class of whatever table it is. In the partial class have the following:

public partial class MyTable{

    partial void OnValidate(System.Data.Linq.ChangeAction action)
    {
        LastEditTime = DateTime.Now;
    }
}

OnValidate is always called before doing a database.submitchanges()

qui
I used it for concurrency check, so can not change it locally.
Rajesh
+1  A: 

The simplest answer would be to assign a default value for the field in the database, i.e. getdate(). Which will ensure the field is populated with the current time/date but only if it's blank.

Linq to SQL is only an access layer on top of SQL so it's fairly dumb in that respect and you'd either need to craft the Linq to SQL classes yourself or ensure that you populate the value when you create your object instance that you are adding to the DB.

If you are looking for something that updates automatically to ensure concurrency every time you update the record then take a look at the timestamp field type.

Lazarus
I agree - let the database do the work.
belugabob
@belugabob Database can do work only on insert.
Rajesh
this will only work for INSERTs not UPDATEs
KM
@KM, you mean the default field value only works on inserts. The timestamp works for both.
Lazarus
A: 

You could create a trigger in the database and assign it to the update action. I know it works, we do this all the time on our Postgres database.

I don´t know if SQL Server has triggers, but you can use a stored procedure.

Luiz Damim