26
        DbParameter param = comm.CreateParameter();
        param = comm.CreateParameter();
        param.ParameterName = "@StaffId";
        if (!string.IsNullOrEmpty(activity.StaffId))
            param.Value = activity.StaffId;
        param.DbType = DbType.String;
        comm.Parameters.Add(param);

The above does not work (obviously), object not instantiated. I am attempting to insert a NULL into the database when StaffId is NOT populated. How can I achieve this?

3

4 Answers 4

49

You can use DBNull.Value when you need to pass NULL as a parameter to the stored procedure.

param.Value = DBNull.Value;

Or you can use that instead of your if operator:

param.Value = !string.IsNullOrEmpty(activity.StaffId) ? activity.StaffId : (object)DBNull.Value;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the edit Andrey - appreciate it. It seems crazy to have to cast this as an object though (to me anyway).
8

Try DBNull.Value

if (!string.IsNullOrEmpty(activity.StaffId))
   param.Value = activity.StaffId;
else
  param.Value=DBNull.Value;

2 Comments

is there a way of using the ? operator for a sort of shorthand if else statement here?? It seems to not like the String/DBNull.Value conversion!?
Try this: param.Value = !string.IsNullOrEmpty(activity.StaffId) ? activity.StaffId : (object)DBNull.Value;
5

You can always use the null-coalescing operator (??)

param.Value = activity.StaffId ?? (object)DBNull.Value;

Comments

3

You could use DBNull.Value:

param.Value = DBNull.Value;

Comments

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.