Giovanni Galbo
Giovanni Galbo

Reputation: 13081

How do you skip default value columns on insert/update in Linq To SQL?

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.

Upvotes: 4

Views: 2384

Answers (3)

Sam
Sam

Reputation: 29009

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

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532515

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.

Upvotes: 5

James Curran
James Curran

Reputation: 103525

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);
    }

Upvotes: 2

Related Questions