下面的代码给出了一个错误——“没有从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;
你需要传递DBNull。值作为SQLCommand中的空参数,除非在存储过程中指定了默认值(如果您使用的是存储过程)。最好的方法是分配DBNull。在查询执行之前为任何缺失的参数赋值,然后使用foreach完成这项工作。
foreach (SqlParameter parameter in sqlCmd.Parameters)
{
if (parameter.Value == null)
{
parameter.Value = DBNull.Value;
}
}
否则更改这一行:
planIndexParameter.Value = (AgeItem.AgeIndex== null) ? DBNull.Value : AgeItem.AgeIndex;
如下:
if (AgeItem.AgeIndex== null)
planIndexParameter.Value = DBNull.Value;
else
planIndexParameter.Value = AgeItem.AgeIndex;
因为在条件语句中不能使用不同类型的值,因为DBNull和int彼此不同。希望这能有所帮助。
你可以这样做。这里startDate和endDate是可空的datetime参数
var Statistics= db.Database.SqlQuery<ViewStatistics>("YourStoreProcedure_Or_sqlQuery @startDate,@endDate",
new SqlParameter("startDate", startDate?? (object)DBNull.Value),
new SqlParameter("endDate", endDate?? (object)DBNull.Value)
).ToList();
你需要传递DBNull。值作为SQLCommand中的空参数,除非在存储过程中指定了默认值(如果您使用的是存储过程)。最好的方法是分配DBNull。在查询执行之前为任何缺失的参数赋值,然后使用foreach完成这项工作。
foreach (SqlParameter parameter in sqlCmd.Parameters)
{
if (parameter.Value == null)
{
parameter.Value = DBNull.Value;
}
}
否则更改这一行:
planIndexParameter.Value = (AgeItem.AgeIndex== null) ? DBNull.Value : AgeItem.AgeIndex;
如下:
if (AgeItem.AgeIndex== null)
planIndexParameter.Value = DBNull.Value;
else
planIndexParameter.Value = AgeItem.AgeIndex;
因为在条件语句中不能使用不同类型的值,因为DBNull和int彼此不同。希望这能有所帮助。