0

I need to use Convert.DBNull for every single null value while adding parameters of sqlCommands. It's tedious because I have a lot of sql commands. So it would be lot easier if there is any way like setting this Object(Convert.DBNull)as parameter whenever it gets a null value as parameter.

Example: I have a code like this:

cmd.Parameters.AddWithValue("@MasterLastModifiedBy", Master.LastModifiedBy);

As variables like Master.LastModifiedBy might be null sometimes, therefore I have to reformat that into this:

cmd.Parameters.AddWithValue("@MasterLastModifiedBy", Master.LastModifiedBy?? Convert.DBNull);

I don't want to do this reformatting in all parameters. So, what else can I do to resolve this problem?

3
  • Write your own extension method AddWithValueWithNiceNullHandling (or whatever name you want) which does the ?? for you. This will thus allow you to still pass null when you explicit want to, but call your new method to use DBNull.Value instead. Commented Jan 21, 2019 at 10:38
  • Please provide the body of the method as answer so that I can mark that as correct one Commented Jan 21, 2019 at 10:47
  • 1
    Honestly @ste-fu's answer is better. Commented Jan 21, 2019 at 10:53

1 Answer 1

1

I would suggest using an ORM Library of some sort. Dapper or Entity Framework would be good places to start.

Or you can write your own method to add a null check to each parameter.

Finally (specifically) thinking about last modified date, you could always set it, which would probably simplify a bunch of queries

EDIT:

Your extension method could look like this:

public static class SqlExtensions // needs to be in a static class
{
    public static void AddWithValueAndNullCheck(this SqlParameterCollection collection, string parameterName, object value)
    {
        if (object == null)
        {
            collection.AddWithValue(parameterName, DBNull.Value);
        }
        else
        {
            collection.AddWithValue(parameterName, value);
        }
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

I am not allowed to use any ORM. Would you please provide the body of that extension method?
Why are you not allowed to use an ORM @Exceptionhandler?
Thanks a lot for the method

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.