views:

1075

answers:

3

How do you insert/update a column through Linq To SQL and Linq To SQL use the default values? In particular I'm concerned with a timestamp field.

I've tried setting that column to readonly and autogenerated, so it stopped trying to put in DateTime.MinValue, but it doesn't seem to be updating on updates.

+2  A: 

The database default value would only insert the value on creating the row. It would do nothing for update, unless you want to add a triggger.

Alternately, you can add a partial method to your DataContext class. Add a new file you your project:

public partial class YourDatabaseDataContext
{
    partial void InsertYourTable(YourTable instance)
    {
        instance.LastUpdateTime = DateTime.Now;

        this.ExecuteDynamicInsert(instance);
    }

    partial void UpdateYourTable(YourTable instance)
    {
        instance.LastUpdateTime = DateTime.Now;

        this.ExecuteDynamicUpdate(instance);
    }
James Curran
+4  A: 

You need to set IsVersion=true for a timestamp column. See the reference for ColumnAttribute.

In the DBML designer for my timestamp columns the properties are set to

AutoGenerated=true
AutoSync=Always
Nullable, Primary Key, and ReadOnly = false
SQLDataType = rowversion not null
Timestamp = true
UpdateCheck = never

I'm assuming that you really mean timestamp and not datetime. If the latter, ignore this.

tvanfosson
+1  A: 

Seems like you just forgot to set AutoSync to always for the property.

Sam