C# 将空值插入TSQL数据库

C# 将空值插入TSQL数据库,c#,database,dbnull,C#,Database,Dbnull,即使我读过有关null和数据库的问题,我也有点结巴。我试图弄清楚如何将NULL发送到数据库表单C#。方法信号是 MyMethod(string category, int? calories, int vegetarianFriendlyMeal); 当使用not null int调用时,它是ok的,但当我传递null时,它会显示 Prepare方法要求所有参数都具有显式设置的类型 您能告诉我如何允许向数据库传递null并在下面的代码中显式设置type吗?多谢各位 co

即使我读过有关null和数据库的问题,我也有点结巴。我试图弄清楚如何将NULL发送到数据库表单C#。方法信号是

MyMethod(string category, int? calories, int vegetarianFriendlyMeal);
当使用not null int调用时,它是ok的,但当我传递null时,它会显示

Prepare方法要求所有参数都具有显式设置的类型

您能告诉我如何允许向数据库传递null并在下面的代码中显式设置type吗?多谢各位

            command.Parameters.Add("@cat", SqlDbType.VarChar, 2).Value = category;
            command.Parameters.Add("@veg", SqlDbType.Int).Value = vegetarianFriendlyMeal;
            if (calories == null)
            {
                command.Parameters.AddWithValue("@calories", DBNull.Value);
            }
            else
            {
                command.Parameters.Add("@calories", SqlDbType.Int).Value = calories;
            }
我也试过了

SqlParameter cal = new SqlParameter("@calories", calories == null ? (object)DBNull.Value : calories);
command.Parameters.Add(cal);
同样的结果。

您是否尝试过:


cmd.Parameters.Add(“@carries”,System.Data.SqlDbType.Int).Value=DBNull.Value

这里的解决方案很简单。在案例1中,.NET使用
AddWithValue
无法推断
DBNull.Value
的关联类型。案例1的解决方案是:

command.Parameters.Add("@cat", SqlDbType.VarChar, 2).Value = category;
command.Parameters.Add("@veg", SqlDbType.Int).Value = vegetarianFriendlyMeal;
if (calories == null)
{
    command.Parameters.Add("@calories", SqlDbType.Int).Value = (object)DBNull.Value;
}
else
{
    command.Parameters.Add("@calories", SqlDbType.Int).Value = calories;
}
在案例2中,您根本不提供类型。解决办法是:

command.Parameters.Add("@cat", SqlDbType.VarChar, 2).Value = category;
command.Parameters.Add("@veg", SqlDbType.Int).Value = vegetarianFriendlyMeal;
SqlParameter cal = new SqlParameter("@calories", calories == null ? (object)DBNull.Value : calories);
cal.DbType = SqlDbType.Int;
command.Parameters.Add(cal);
但如果你想把它弄干净,你可以这样做:

command.Parameters.Add("@cat", SqlDbType.VarChar, 2).Value = category;
command.Parameters.Add("@veg", SqlDbType.Int).Value = vegetarianFriendlyMeal;
command.Parameters.Add("@calories", SqlDbType.Int).Value = calories ?? (object)DBNull.Value;

编辑:不要使用
AddWithValue
。让.NET为您填补漏洞是有风险的。

使用
.Value=carries??(object)DBNull.Value应该可以正常工作。唯一的区别是值,那么为什么要以两种不同的方式创建参数?您确定这就是全部代码吗?我一眼就看不出有什么问题。查询中还有其他参数吗?@Luaan谢谢这同样有效并保存了that if语句。谢谢。我通常使用.Add,但在这里我被卡住了,希望.AddWithValue能帮我解决这个问题。