106

I have following code for specifying parameters for SQL query. I am getting following exception when I use Code 1; but works fine when I use Code 2. In Code 2 we have a check for null and hence a if..else block.

Exception:

The parameterized query '(@application_ex_id nvarchar(4000))SELECT E.application_ex_id A' expects the parameter '@application_ex_id', which was not supplied.

Code 1:

command.Parameters.AddWithValue("@application_ex_id", logSearch.LogID);

Code 2:

if (logSearch.LogID != null)
{
         command.Parameters.AddWithValue("@application_ex_id", logSearch.LogID);
}
else
{
        command.Parameters.AddWithValue("@application_ex_id", DBNull.Value );
}

QUESTION

  1. Can you please explain why it is unable to take NULL from logSearch.LogID value in Code 1 (but able to accept DBNull)?

  2. Is there a better code to handle this?

Reference:

  1. Assign null to a SqlParameter
  2. Datatype returned varies based on data in table
  3. Conversion error from database smallint into C# nullable int
  4. What is the point of DBNull?

CODE

    public Collection<Log> GetLogs(LogSearch logSearch)
    {
        Collection<Log> logs = new Collection<Log>();

        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();

            string commandText = @"SELECT  *
                FROM Application_Ex E 
                WHERE  (E.application_ex_id = @application_ex_id OR @application_ex_id IS NULL)";

            using (SqlCommand command = new SqlCommand(commandText, connection))
            {
                command.CommandType = System.Data.CommandType.Text;

                //Parameter value setting
                //command.Parameters.AddWithValue("@application_ex_id", logSearch.LogID);
                if (logSearch.LogID != null)
                {
                    command.Parameters.AddWithValue("@application_ex_id", logSearch.LogID);
                }
                else
                {
                    command.Parameters.AddWithValue("@application_ex_id", DBNull.Value );
                }

                using (SqlDataReader reader = command.ExecuteReader())
                {
                    if (reader.HasRows)
                    {
                        Collection<Object> entityList = new Collection<Object>();
                        entityList.Add(new Log());

                        ArrayList records = EntityDataMappingHelper.SelectRecords(entityList, reader);

                        for (int i = 0; i < records.Count; i++)
                        {
                            Log log = new Log();
                            Dictionary<string, object> currentRecord = (Dictionary<string, object>)records[i];
                            EntityDataMappingHelper.FillEntityFromRecord(log, currentRecord);
                            logs.Add(log);
                        }
                    }

                    //reader.Close();
                }
            }
        }

        return logs;
    }
Community
  • 1
  • 1
LCJ
  • 22,196
  • 67
  • 260
  • 418

4 Answers4

175

Annoying, isn't it.

You can use:

command.Parameters.AddWithValue("@application_ex_id",
       ((object)logSearch.LogID) ?? DBNull.Value);

Or alternatively, use a tool like "dapper", which will do all that messing for you.

For example:

var data = conn.Query<SomeType>(commandText,
      new { application_ex_id = logSearch.LogID }).ToList();

I'm tempted to add a method to dapper to get the IDataReader... not really sure yet whether it is a good idea.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • @Phil indeed; most things can... but I don't like adding extension methods on `object`, and we can't see whether that is `Nullable` vs `string`, etc... but yes: it could be done easily enough. – Marc Gravell Nov 19 '12 at 09:47
  • 1
    I was thinking an extension on the `Parameters` property - is that an `Object`? – Phil Gan Nov 19 '12 at 09:48
  • 6
    @Phil hmmm, yes it is, and I see what you mean... maybe `AddWithValueAndTreatNullTheRightDamnedWay(...)` – Marc Gravell Nov 19 '12 at 09:49
  • 1
    @MarcGravell Can you please explain why it is unable to take NULL from logSearch.LogID value in Code 1 (but able to accept DBNull)? – LCJ Nov 19 '12 at 09:53
  • 19
    @Lijo because `null` in a parameter value means "don't send this parameter". I suspect it was a bad decision that simply got baked in. In fact, I think **most** of `DBNull` was a fundamentally bad decision that got baked in: http://stackoverflow.com/a/9632050/23354 – Marc Gravell Nov 19 '12 at 10:17
  • Why is there the need to put `(object)` before `logSearch.LogID` here? – TylerH May 21 '20 at 19:07
  • 1
    @tylerH because of the null coale cast rules - which may be weakening in C#9 – Marc Gravell May 23 '20 at 08:17
61

I find it easier to just write an extension method for the SqlParameterCollection that handles null values:

public static SqlParameter AddWithNullableValue(
    this SqlParameterCollection collection,
    string parameterName,
    object value)
{
    if(value == null)
        return collection.AddWithValue(parameterName, DBNull.Value);
    else
        return collection.AddWithValue(parameterName, value);
}

Then you just call it like:

sqlCommand.Parameters.AddWithNullableValue(key, value);
Kapol
  • 6,383
  • 3
  • 21
  • 46
AxiomaticNexus
  • 6,190
  • 3
  • 41
  • 61
  • _value_ can be **int or int?, string, bool or bool?, DateTime or Datetime?**, etc ? – Kiquenet Apr 13 '15 at 07:03
  • 3
    I read Marc's answer and thought "I think I'd rather just write an extension method for the Parameters collection", then I scrolled down a hair... (nice thing about an extension method is that I can do a single find/replace after and all my code updates are done) – jleach Jan 05 '16 at 15:59
  • 1
    Great solution...Extension methods must be defined in a static class. [How to: Implement and Call a Custom Extension Method](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-implement-and-call-a-custom-extension-method) – Chris Catignani Nov 16 '17 at 20:02
  • 3
    Maybe I am mistaken (kind of a C# newbie) but couldn't you do it more concisely like this: `return collection.AddWithValue(parameterName, value ?? DBNull.Value);` – Tobias Feil Apr 02 '19 at 08:08
  • 1
    @TobiasFeil Yes, you could do that too. It's just a matter of taste. – AxiomaticNexus Apr 03 '19 at 13:46
  • Works with VB.NET as well after applying the `` attribute – Burhan Sep 16 '21 at 16:23
4

Just in case you're doing this while calling a stored procedure: I think it's easier to read if you declare a default value on the parameter and add it only when necessary.

SQL:

DECLARE PROCEDURE myprocedure
    @myparameter [int] = NULL
AS BEGIN

C#:

int? myvalue = initMyValue();
if (myvalue.hasValue) cmd.Parameters.AddWithValue("myparamater", myvalue);
TylerH
  • 20,799
  • 66
  • 75
  • 101
z00l
  • 895
  • 11
  • 21
0

some problem, allowed with Necessarily set SQLDbType

command.Parameters.Add("@Name", SqlDbType.NVarChar);
command.Parameters.Value=DBNull.Value

where SqlDbType.NVarChar you type. Necessarily set SQL type.

TylerH
  • 20,799
  • 66
  • 75
  • 101