views:

589

answers:

4

When using Linq-to-SQL, adding a column to an existing table, and setting a default value on that new column, it seems that Linq to SQL ignores the default value. Has anyone else experienced this behaviour? Is there a way to fix it, so that Linq-to-SQL or SQL Server automatically sets the default value?

The column I added was of type Bit, with a default value set to 1.

+1  A: 

I've seen this. What you can do is go into the l2sql designer, view properties for the table column that has a default value. There is a property "Auto generated value", set that to true.

This same value is set to true automatically for the identity column automatically, as in that case SQL Server is generating your row IDs.

Frank Schwieterman
This is not working, as I need to update the column afterwards. When I try your solution I get an error: "A member calculated or generated in the database can not be changed"
jao
Thats too bad. I never tried it with a field I wanted to change later (I was using it for a DateCreated column). Even in that case I decided not to use a SQL default value and set it explicitly in my code- the reasoning being its part of my domain logic so it belongs with the rest of my domain logic code.
Frank Schwieterman
I think the error I get is a bug in Linq-to-sql. The tooltip of 'auto generated value' says "Value is autogenerated on insert"
jao
A: 

I've now temporarily fixed this by explicitly setting the value in my Add function, until someone posts a better answer.

public void Add(Foo foo) {
        foo.isnew = true;
        db.Foos.InsertOnSubmit(foo);
}
jao
A: 

Go into the designer and select "Auto-Sync" value of "OnInsert". This will sync the value when the record is inserted into the database.

Nicholas H
+2  A: 

I have now definitively fixed this by using an example from this blog.

partial void OnCreated() {
    if (this.DateTimeCreated == null) {
           this.DateTimeCreated = DateTime.Now;
    }
}

I needed to pass this into a partial datacontext class, as the default one is automatically overwritten every time you change something in the dbml.

jao
Does my solution not fix the problem?
Nicholas H
your solution works on insert, but when I update the record I get an error about some member generated in the database cannot be changed
jao