有没有一种简单的方法可以检查多个列以查看该值是否为空?

时间:2011-12-06 21:22:29

标签: c# asp.net

我正在获取参数并从存储过程中获取特定产品。这个存储过程返回许多列(我认为大约15-20)。不幸的是,其中一些值可能为null,当我尝试将它们放入变量时,这当然会产生错误。有没有一种简单的方法来检查并查看这些值是否为NULL,以便它不会抛出异常,或者我是否需要在每次赋值之前放置if语句?如果有帮助,这是我的代码:

public List<Product> ReadSpecificProductDetails(string productAndURLID)
    {
        ConfigureDataAccess();
        myCommand = new SqlCommand("[dbo].[GetSpecificProductDetails]", myConnection);
        myCommand.CommandType = CommandType.StoredProcedure;
        //myCommand.Parameters.Add(productAndURLID);
        //myCommand.Parameters.Add(new SqlParameter("@ProductID", SqlDbType.SmallInt));
        myCommand.Parameters.AddWithValue("@ProductID", Convert.ToInt16(productAndURLID));

        try
        {
            try
            {
                myConnection.Open();
                myReader = myCommand.ExecuteReader();
            }
            catch (SqlException exception)
            {
                exception.Data.Add("cstring", myConfiguration);
                throw;
            }
            catch (InvalidOperationException ex)
            {
                ex.Data.Add("cStatus", myConnection.State);
                throw;
            }

            //Create a 'Product' list to store the records in
            while (myReader.Read())
            {
                int productID = Convert.ToInt16(myReader["ProductID"]);
                string productName = (string)myReader["Name"];
                string productNumber = (string)myReader["ProductNumber"];
                //int quantitySum = Convert.ToInt16(myReader["QuantitySum"]);
                string productColor = (string)myReader["Color"];
                int productSafetyStockLevel = Convert.ToInt16(myReader["SafetyStockLevel"]);
                int productReorderPoint = Convert.ToInt16(myReader["ReorderPoint"]);
                decimal productStandardCost = Convert.ToDecimal(myReader["StandardCost"]);
                decimal productListPrice = Convert.ToDecimal(myReader["ListPrice"]);
                string productSize = (string)myReader["Size"];
                decimal productWeight = Convert.ToDecimal(myReader["Weight"]);
                int productDaysToManufacture = Convert.ToInt16(myReader["DaysToManufacture"]);
                string productCategoryName = (string)myReader["PC.Name"];
                string productSubCategoryName = (string)myReader["PS.Name"];
                string productModelName = (string)myReader["PM.Name"];
                DateTime productSellStartDate = Convert.ToDateTime(myReader["Sell_Start_Date"]);
                DateTime productSellEndDate = Convert.ToDateTime(myReader["Sell_End_Date"]);
                DateTime productDiscontinuedDate = Convert.ToDateTime(myReader["Discontinued_Date"]);
                Product p = new Product(productID, productName, productNumber, productColor, productSafetyStockLevel, productReorderPoint, productStandardCost,
                    productListPrice, productSize, productWeight, productDaysToManufacture, productCategoryName, productSubCategoryName, productModelName, productSellStartDate,
                    productSellEndDate, productDiscontinuedDate);
                myProducts.Add(p);
            }
        }
        finally
        {
            myReader.Close();
            myConnection.Close();
        }
        return myProducts;
    }

4 个答案:

答案 0 :(得分:7)

int? x = dt.Field<int?>( "Field" );

或者

int y = dt.Field<int?>( "Field" ) ?? 0;

C# DBNull and nullable Types - cleanest form of conversion

顶部可能是你最好的方法。您目前正在填充一些不可为空的类型。因此,如果您希望能够将它们表示为null,请使用top方法。否则,您可以使用其他选项来提供默认值。

答案 1 :(得分:1)

LINQ将成为你在这些情况下最好的朋友,就像评论中提到的ssg一样,但是如果你想进行大量的空检查,你可以实现如下内容:

int productID = (myReader["ProductID"] != null) ? Convert.ToInt16(myReader["ProductID"]) : 0;

或者你可以简单地使用if语句。

答案 2 :(得分:0)

对可能怀疑为空值的字段执行DBNULL检查。在这种情况下所有这些。

if (! DBNull.Value.Equals(row[fieldName])) 
      return (string) row[fieldName] + " ";
   else
      return String.Empty;

您可以做的是创建一个函数,该函数对检查null的int,string和DateTime参数有多个重载

所以它看起来像这样:

public string CheckNull(string value)
{
   if (! DBNull.Value.Equals(value)) 
          return value;
       else
          return String.Empty;
}

这样你只需做类似

的事情
object.stringProperty = (string)CheckNull(row["columnName"]);

答案 3 :(得分:0)

当使用数据读取器和DTO之间的直接映射时,我使用数据读取器的IsDbNull()方法。以下是使用不同数据类型的几个示例:

myObj.MyStringProperty = !myReader.IsDBNull("myStringColumn") ? myReader["myStringColumn"].ToString() : null;
myObj.MyNullableDecimalProperty = !myReader.IsDBNull("mydecimalColumn") ? decimal.Parse(myReader["mydecimalColumn"].ToString()) : new decimal?();
相关问题