下面的代码给出了一个错误——“没有从DBnull到int的隐式转换”。

SqlParameter[] parameters = new SqlParameter[1];    
SqlParameter planIndexParameter = new SqlParameter("@AgeIndex", SqlDbType.Int);
planIndexParameter.Value = (AgeItem.AgeIndex== null) ? DBNull.Value : AgeItem.AgeIndex;
parameters[0] = planIndexParameter;

当前回答

如果使用条件(三元)操作符,编译器需要在两种类型之间进行隐式转换,否则会出现异常。

所以你可以通过将两者之一强制转换为系统来修复它。对象:

planIndexParameter.Value = (AgeItem.AgeIndex== null) ? DBNull.Value : (object) AgeItem.AgeIndex;

但是因为结果不是很漂亮,你总是要记住这个类型转换,你可以使用这样一个扩展方法:

public static object GetDBNullOrValue<T>(this T val)
{
    bool isDbNull = true;
    Type t = typeof(T);

    if (Nullable.GetUnderlyingType(t) != null)
        isDbNull = EqualityComparer<T>.Default.Equals(default(T), val);
    else if (t.IsValueType)
        isDbNull = false;
    else
        isDbNull = val == null;

    return isDbNull ? DBNull.Value : (object) val;
}

然后你可以使用以下简洁的代码:

planIndexParameter.Value = AgeItem.AgeIndex.GetDBNullOrValue();

其他回答

在我看来,更好的方法是使用SqlCommand类的Parameters属性:

public static void AddCommandParameter(SqlCommand myCommand)
{
    myCommand.Parameters.AddWithValue(
        "@AgeIndex",
        (AgeItem.AgeIndex== null) ? DBNull.Value : AgeItem.AgeIndex);
}

一个简单的扩展方法是:

    public static void AddParameter(this SqlCommand sqlCommand, string parameterName, 
        SqlDbType sqlDbType, object item)
    {
        sqlCommand.Parameters.Add(parameterName, sqlDbType).Value = item ?? DBNull.Value;
    }

考虑使用可用的Nullable(T)结构。它将允许您仅在拥有值时设置值,SQL Command对象将识别可为空的值并进行相应的处理,而不会给您带来麻烦。

如果使用条件(三元)操作符,编译器需要在两种类型之间进行隐式转换,否则会出现异常。

所以你可以通过将两者之一强制转换为系统来修复它。对象:

planIndexParameter.Value = (AgeItem.AgeIndex== null) ? DBNull.Value : (object) AgeItem.AgeIndex;

但是因为结果不是很漂亮,你总是要记住这个类型转换,你可以使用这样一个扩展方法:

public static object GetDBNullOrValue<T>(this T val)
{
    bool isDbNull = true;
    Type t = typeof(T);

    if (Nullable.GetUnderlyingType(t) != null)
        isDbNull = EqualityComparer<T>.Default.Equals(default(T), val);
    else if (t.IsValueType)
        isDbNull = false;
    else
        isDbNull = val == null;

    return isDbNull ? DBNull.Value : (object) val;
}

然后你可以使用以下简洁的代码:

planIndexParameter.Value = AgeItem.AgeIndex.GetDBNullOrValue();
sqlCom.Parameters.Add(new SqlParameter("@qavCode", SqlDbType.Char, 11)).Value = (object)(string.IsNullOrEmpty(rf.Request.QavCode) ? null : rf.Request.QavCode) ?? DBNull.Value;

改进空合并操作符的使用??在我的例子中,为了管理空字符串,我将常规三元?:混合到空并合运算符??希望我的建议是有用的。