NLog - Write NULL to optional database column
NLog ver. 4.7.4 adds the parameter-option AllowDbNull
so you can do like this:
<parameter name="@exception" layout="${exception:format=tostring}" allowDbNull="true" />
<parameter name="@correlationid" layout="${activityid}" dbType="DbType.Guid" allowDbNull="true" />
Nlog will automatically convert empty-string/no-output to DbNull-value when allowDbNull="true"
.
NLog uses StringBuilder to make parameter value. Even if a parameter isn't specified it initializes a value as builder.ToString() which is empty string.
You may change your commandText like this:
INSERT INTO [dbo].[log] ([message], [optional])
VALUES
(
@message,
case
when len(@optional) = 0 then null
else @optional
end
)
It seems like a hack for me though. I hope there is a better solution.
This is an old question but due to the solutions given are a little 'hacky' I wanted to give my own which I consider it is way more simple to implement than a db procedure and more elegant that using a case.
You can try to write the NULL with the NULLIF
function that compares 2 expressions and returns NULL if they are equal, otherwise it returns the first expression (msdn NULLIF page).
This way the commandText on your NLog config file would look like:
INSERT INTO [dbo].[log] ([message], [optional])
VALUES (@message, NULLIF(@optional, ''))