我试图调用具有INT参数(BusinessID)并允许NULL的存储过程。从我的C#代码中,我无法确定数据是否为空,如何识别和传递。我列出了我尝试过的三种技术,编号为#1,#2,#3和出现的错误。请指导 这是我的示例代码:
private static DataRow ValidateRecord (string ProjectNum, int? BusinessID)
{
DataRow returnRow = null;
using (SqlConnection connection = Connection.GetConnection())
{
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
try
{
using (SqlCommand command = new SqlCommand(
"[dbo].[mySQLProc]", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.CommandTimeout = 90;
command.Parameters.Add("@ProjectNum", SqlDbType.VarChar, 17).Value = ProjectNum;
// #1 – error: "Data is Null. This method or property cannot be called on Null values."
//if (!BusinessID.HasValue)
//{
// BusinessID = (int)System.Data.SqlTypes.SqlInt32.Null;
//}
//#2 - "Data is Null. This method or property cannot be called on Null values."
if (BusinessID == null)
{
BusinessID = (int)System.Data.SqlTypes.SqlInt32.Null;
}
//#3 - error on compile time – Type of conditional expression cannot be determined because
// there is no implicit converstion between ‘System.DBNull’ and ‘int?’
// BusinessID = BusinessID == null ? DBNull.Value : BusinessID;
command.Parameters.Add("@BusinessID", SqlDbType.Int).Value = BusinessID;
command.ExecuteNonQuery();
connection.Close();
returnRow = CreateDataRow(ProjectNum, BusinessID);
}
}
catch (Exception ex)
{
throw ex;
}
return returnRow;
}
}