I have an SQL Server DB with a table with these fields:
bit
with the default value 1, NOT NULL
.smalldatetime
I've run into the same problem, bzlm, and come to the same conclusion. There's simply no good way to get non-nullable fields with DB-assigned default values working with Linq To Sql.
The work around I've gone with is to add a SetDefaults() method very similar to the one Robert Paulson linked to on CodeProject and call it in the default constructor of my table entity base class. It works well for me, because 95% of the time, I'm setting a 0, empty string, or getdate().
This means that when I make inserts using Linq to SQL, the following will happen:
- The bit will be sent as 0, overriding the default value. Right? - Correct
- The smalldatetime will be sent as an uninitialized System.DateTime, producing an error in SQL server since it doesn't fall with the SQL Server smalldatetime range. Right? - What is sent is DateTime.MinValue
- The IsDbGenerated int will not be sent; the DB will generate a value which Linq to SQL will then read back. - If DB generated is set then the value is created by the database, if not then Linq expects the user to set the value.
Your best bet is to set them in the constructor of the object, or on the private fields, if you are not using automatic properties.
You can create another file for your datacontext (partial class) and then use the InsertYOURENTITY and UpdateYOURENTITY partial methods to inspect your properties and assign the proper values. Call ExecuteDynamicInsert or ExecuteDynamicUpdate after your code and you're set.
Linq-To-Sql generated classes do not pick up the Default Value Constriants.
Maybe in the future, but the issue is constraints aren't always simple values, they can also be scalar functions like GetDate()
, so linq would somehow have to know how to translate those. In short, it doesn't even try. It's also a very database-specific type of thing.
The issue you are having is described at length in CodeProject - Setting Default Values for LINQ Bound Data