C#诠释?参数-数据为空。不能在Null值上调用此方法或属性

时间:2019-03-08 19:11:58

标签: c# stored-procedures null int

我试图调用具有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;
    }
}

0 个答案:

没有答案