I have an SQL Server DB with a table with these fields:
- A
bitwith the default value 1,NOT NULL. - A
smalldatetimewith the default valuegettime(),NOT NULL. - An
intwith no default value,IDENTITY,NOT NULL.
When I generate Linq to SQL for this table, the following happens:
- The
bitis given no special treatment. - The
smalldatetimeis given no special treatment. - The
intis marked asIsDbGenerated.
This means that when I make inserts using Linq to SQL, the following will happen:
- The
bitwill be sent as 0, overriding the default value. Right? - The
smalldatetimewill be sent as an uninitializedSystem.DateTime, producing an error in SQL server since it doesn’t fall with the SQL Server smalldatetime range. Right? - The
IsDbGeneratedintwill not be sent; the DB will generate a value which Linq to SQL will then read back.
What changes do I have to make to make this scenario work?
To summarize: I want non-nullable fields with DB-assigned default values, but I don’t want them IsDbGenerated if it means I cannot provide values for them when making updates or inserts using Linq to SQL. I also do not want them IsDbGenerated if it means I have to hand-modify the code generated by Linq to SQL.
EDIT: The answer seems to be this is a limitation in the current Linq to SQL.
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