Skip to content
Advertisement

C# INSERT to SQL method exception when DateTime parameter is null

One of my parameter looks like this:

cmd.Parameters.Add("@last_sign_in_at", SqlDbType.DateTime).Value = user.last_sign_in_at;

I know that User has null value in last_sign_in_at. Database accept nulls for this column but I get an exception:

SqlException: The parameterized query ‘(@id int,@name nvarchar(18),@username nvarchar(11),@state nvarch’ expects the parameter ‘@last_sign_in_at’, which was not supplied.

Advertisement

Answer

You should be using DBNull.Value:

cmd.Parameters.Add("@last_sign_in_at", SqlDbType.DateTime).Value = (object)user.last_sign_in_at ?? (object)DBNull.Value;

Casting to object here is just for operator ?? to not complain about different types

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement