Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 695
Giovanni Galbo Avatar asked Mar 01 '23 06:03

Giovanni Galbo


2 Answers

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.

like image 173
tvanfosson Avatar answered Mar 04 '23 16:03

tvanfosson


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);
    }
like image 20
James Curran Avatar answered Mar 04 '23 16:03

James Curran