In my data layer class, I initialize a parameter like so:
private int? _DependencyID;
public int? DependencyID
{ get {return _DependencyID;} set {_DependencyID
You need to add an object
:
cmd.AddWithValue("@DependencyID", _DependencyID == null? DBNull.Value : (object)_DependencyID);
You can shorten that to
cmd.AddWithValue("@DependencyID", (object)_DependencyID ?? DBNull.Value);
I have created an extension to simply the code.
public static class SQLExtension
{
public static SqlParameter AddWithNullable<T>(
this SqlParameterCollection collection,
string parameterName,
Nullable<T> value) where T : struct, IComparable
{
return collection.AddWithValue(
parameterName, (value.HasValue ? value.Value : (object)DBNull.Value)
);
}
}
Here is how you can use it.
cmd.AddWithNullable("@DependencyID", _DependencyID);
AFAIC, ADO.NET/SQL don't support nullable types this way.
The last example looks closest to correct to me. What kind of issues are you having with it? If you are just getting a compile error related to types, type cast your value to object:
(object)DependencyID.Value;
Since both values on either side of :
must be of the same type.