我收到一个参数并从存储过程获取特定产品。这个存储过程返回很多列(我认为大约15-20)。不幸的是,其中一些值可能为空,当我尝试将它们放入一个变量中时,这当然会产生错误。是否有简单的方法来检查并查看这些值是否为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;
}
我强烈建议使用LINQ-to-SQL将您的数据库映射到类中,这使得这些事情变得非常简单和容易。 –