1

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.

1
  • Tip: if you use Dapper, it get things like this right for you, and avoids a lot of code: connection.Execute(@"...SQL...", new { user.last_sign_in_at }); Commented Nov 3, 2020 at 16:57

2 Answers 2

5

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

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

4 Comments

Operator '??' cannot be applied to operands of type 'DateTime?' and 'DBNull'
expected that, you could use (object)user.last_sign_in_at?? (object)DBNull.Value
I used cmd.Parameters.Add("@last_sign_in_at", SqlDbType.DateTime).Value = user.last_sign_in_at ?? DateTime.Today;
but that's not null, what do you mean? You inserted Today's time, you should use DBNull.Value, that's also obviously if your column is Nullable in SQL Table
1

When using raw .net framework, I've always had to use the value DBNull.Value.

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

1 Comment

but user.last_sign_in_at is not always NULL but when it's null method trows an exception

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.