I have a SQL table where column is set to null. Now I am passing the null value from code via stored procedure and it throws an error which is, Procedure or function 'MyStoredProcedure' expects parameter '@Parameter', which was not supplied.
Now Confusing part for me is, if I add null condition and than pass DBNull.Value, it works fine but if I pass direct parameter which could be null than it throws error. I am trying to understand why? Am I missing something here?
Note: Just for information, passing parameter could be null based on the requirement.
Code:
string connString = _dbContext.Database.Connection.ConnectionString;
using (SqlConnection connection = new SqlConnection(connString))
{
connection.Open();
SqlCommand cmd = new SqlCommand("MyStoredProcedure", connection);
cmd.CommandType = CommandType.StoredProcedure;
scheduledEndDateTime = !string.IsNullOrEmpty(bulkUpdateSchedule.EndDate) && !string.IsNullOrEmpty(bulkUpdateSchedule.EndTime)
? (DateTime?)
Convert.ToDateTime(bulkUpdateSchedule.EndDate + " " + bulkUpdateSchedule.EndTime)
: null;
//This Fails
cmd.Parameters.AddWithValue("@scheduledEndDateTime", scheduledEndDateTime);
//This Works
if (scheduledEndDateTime != null)
{
cmd.Parameters.AddWithValue("@scheduledEndDateTime", scheduledEndDateTime);
}
else
{
cmd.Parameters.AddWithValue("@scheduledEndDateTime", DBNull.Value);
}
cmd.ExecuteReader();
connection.Close();
}
Stored Procedure:
ALTER PROCEDURE [dbo].[InsertScheduledBulkUpdateRecords]
@scheduledEndDateTime DATETIME,
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO ScheduledBulkUpdate (ScheduledEndDateTime)
VALUES (@scheduledEndDateTime)
END
Table Structure screen shot:

DBNulland c#nullare different things@scheduledEndDateTime DATETIME = nullif...elseroute.AddWithValue()sucks some of the time.if...elseyou can potentially use(object)scheduledEndDateTime ?? DBNull.Valueto coalese the null value. See ?? on MSDN. Note: you need the object cast to make the two sides comparable.