如何控制查询结果是null还是为空

本文关键字:null 结果是 查询 何控制 控制 | 更新日期: 2023-09-27 17:57:30

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

我该怎么做?

如何控制查询结果是null还是为空

我通常把它们写成:

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.

尝试使用空合并运算符

PicturePath = GetString(6) ?? "Noimage.jpg",

尝试IsDBNull:

if(dr.IsDBNull(6))
PicturePath = "Noimage.jpg";
else
PicturePath = dr.GetString(6);