我的项目中有SqlConnection,我想控制我的查询结果
public IEnumerable<Product> ListPrpductByCategory(int ID)
{
var dr = db.ExecuteReader(@"SELECT P.ID,P.CategoryID,P.Name,P.SupplierID,p.UnitPrice,p.UnitsInStock,pp.PicturePath
FROM Products P
LEFT JOIN ProductPhoto PP ON p.ID=PP.ProductID
WHERE P.CategoryID=@ID",
Values: new object[] { ID });
while (dr.Read())
{
yield return new Product()
{
ID = dr.GetInt32(0),
CategoryID = dr.GetInt32(1),
SupplierID = dr.GetInt32(3),
Name = dr.GetString(2),
UnitPrice = dr.GetDecimal(4),
UnitInstock = dr.GetInt16(5),
PicturePath = dr.GetString(6)
};
}
dr.Close();
//...
}
如果没有图片则会引发错误我想控制dr.GetString(6)
喜欢
if(dr.GetString(6)==null)
PicturePath="Noimage.jpg";
我该怎么做?
答案 0 :(得分:3)
我通常把它们写成:
PicturePath = dr.IsDBNull(6) ? "Noimage.jpg" : dr.GetString(6)
此外,您应该将数据阅读器包装在using
语句中:
using(var dr = db.ExecuteReader(...))
{
while (dr.Read())
{
...
}
} //no need to call Close, as Dispose already closes the reader.
答案 1 :(得分:2)
PicturePath = GetString(6) ?? "Noimage.jpg",
答案 2 :(得分:1)
尝试IsDBNull:
if(dr.IsDBNull(6))
PicturePath = "Noimage.jpg";
else
PicturePath = dr.GetString(6);