Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

{"Parameter must have its value set"} dealing with possible null values in NPGSQL

I have a parameter that can take can either be a long or null,

here is my code

        public List<blahOject>GetBlahNOde(long? p_test)
        {
                    ...


                    cmd.Parameters.Add(new NpgsqlParameter
                    {
                        ParameterName = "test",
                        Value = p_test
                    });

        }

when i try to run my method i can an error of

{"Parameter 'test' must have its value set"}

not sure how to make this work with possible null values, p_test isnt always null and sometimes contains a value

like image 914
dros Avatar asked Nov 25 '25 15:11

dros


2 Answers

To represent a null parameter value, set Value to DBNull.Instance, not null.

like image 158
Shay Rojansky Avatar answered Nov 27 '25 03:11

Shay Rojansky



private static NpgsqlParameter safeNpgsqlParameter<T>( string parameterName, T? data ) where T : struct =>
    data switch {
        decimal => new NpgsqlParameter() { ParameterName = parameterName, NpgsqlDbType = NpgsqlDbType.Numeric, Value = data },
        Enum    => new NpgsqlParameter() { ParameterName = parameterName, Value = data },
        null    => new NpgsqlParameter() { ParameterName = parameterName, Value = DBNull.Value },
        LocalDate => new NpgsqlParameter() {
            ParameterName = parameterName,
            NpgsqlDbType  = NpgsqlDbType.Date,
            Value         = data
        },
        _ => throw new DbUpdateException()
    };

Use like:

// spec.Date is of type LocalDate?
cmd.Parameters.Add( safeNpgsqlParameter( "SomeDateParam", spec.Date ) );

// spec.MyEnum is of type MyEnum?
cmd.Parameters.Add( safeNpgsqlParameter( "MyEnumParam", spec.MyEnum ) );

// spec.Qty is of type decimal?
cmd.Parameters.Add( safeNpgsqlParameter( "SomeNumericParam", spec.Qty ) );

And of course other types could be added to the switch within safeNpgsqlParameter

like image 42
ehiller Avatar answered Nov 27 '25 03:11

ehiller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!