0

我的项目中有 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";

我怎样才能做到这一点?

4

3 回答 3

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.
于 2013-02-04T01:04:54.300 回答
2

尝试使用空合并运算符

PicturePath = GetString(6) ?? "Noimage.jpg",
于 2013-02-04T00:03:05.453 回答
1

尝试IsDBNull

if(dr.IsDBNull(6))
PicturePath = "Noimage.jpg";
else
PicturePath = dr.GetString(6);
于 2013-02-04T00:03:33.813 回答