I have a LINQ to SQL class “VoucherRecord” based on a simple table. One property “Note” is a string that represents an nvarchar(255) column, which is non-nullable and has a default value of empty string (”).
If I instantiate a VoucherRecord the initial value of the Note property is null. If I add it using a DataContext’s InsertOnSubmit method, I get a SQL error message:
Cannot insert the value
NULLinto column'Note', table'foo.bar.tblVoucher'; column does not allow nulls.INSERTfails.
Why isn’t the database default kicking in? What sort of query could bypass the default anyway? How do I view the generated sql for this action?
Thanks for your help!
If you omit the column, the value becomes the database default, but anything you insert is used instead of the default, example:
Picture for example you have a column that defaults to anything but
NULL, but you specifically wantNULL…for that to ever work, whatever value you specify MUST override the default, even in the case ofNULL.You need to set Auto-Sync to
OnInsert, Auto Generated Value totrueand Nullable tofalsefor your column to work. See here for a full run-down with explanation on the Linq side.For viewing the generated SQL, I have to recommend LinqPad