2

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 NULL into column 'Note', table 'foo.bar.tblVoucher'; column does not allow nulls. INSERT fails.

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!

1 Answer 1

2

If you omit the column, the value becomes the database default, but anything you insert is used instead of the default, example:

INSERT INTO MyTable (ID, VoucherRecord) Values(34, NULL) -- Null is used
INSERT INTO MyTable (ID) Values(34) -- Default is used

Picture for example you have a column that defaults to anything but NULL, but you specifically want NULL...for that to ever work, whatever value you specify MUST override the default, even in the case of NULL.

You need to set Auto-Sync to OnInsert, Auto Generated Value to true and Nullable to false for 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

Sign up to request clarification or add additional context in comments.

7 Comments

I see what you mean. But if I set my Note column to AutoGenerated = true, I can't set its value, which is bad. I get the error " Value of member 'Note' of an object of type 'VoucherRecord' changed. A member that is computed or generated by the database cannot be changed."
And if I only set AutoSync to Insert without setting AutoGenerated to True, I return to the original error message. Hmm!
@Barry - Do you have Nullable set to false in your Linq model?
Yes, Nullable is set to false.
@Barry - Try this partial to go with the same class: public partial class VoucherRecord { partial void OnCreated() { Note = Note ?? string.Empty; } } Leaving AutoGenerated set to false
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.