代码:
public List<ProductDTO> GetAllProducts()
{
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
string query = "SELECT * FROM [dbo].[Product]";
using (SqlCommand cmd = new SqlCommand(query, con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
List<ProductDTO> allProducts = new List<ProductDTO>();
while (reader.Read())
{
ProductDTO product = new ProductDTO
{
ProductID = Convert.ToInt32(reader["ProductID"]),
SellerID = Convert.ToInt32(reader["UserID"]),
Name = reader["Name"].ToString(),
Price = Convert.ToDecimal(reader["Price"]),
Photo = reader["Photo"].ToString(),
Likes = Convert.ToInt32(reader["Likes"]), //error occurs only when Likes is not commented out
Description = reader["Description"].ToString(),
Category = (Enums.ProductCategory.Category)reader["CategoryID"] - 1
};
allProducts.Add(product);
}
return allProducts;
}
}
}
catch (Exception)
{
return new List<ProductDTO>();
}
}
我的问题是:在实例化ProductDTO时如何进行Object cannot be cast from DBNull to other types这样的检查?