我该如何处理这个NULL数据?

时间:2017-06-14 13:26:59

标签: c# sql-server

我有下表:

CREATE TABLE [dbo].[CATEGORIE](
    [bijdrage_id] [int] NOT NULL,
    [categorie_id] [int] NULL,
    [naam] [nvarchar](255) NOT NULL,)

我使用此查询来检索数据:

select c.bijdrage_id, c.categorie_id AS Subcategorievan, c.Naam from CATEGORIE as c

使用以下c#代码,我将所有值都放入Categorie对象中:

public List<Categorie> geefAlleCategorien()
        {
            List<Categorie> categorien = new List<Categorie>();
            string query = "select c.bijdrage_id, c.categorie_id as SubCategorieVan, c.Naam from CATEGORIE as c";
            SqlDataReader reader = db.Select(query);
            while (reader.Read())
            {
                Categorie c = new Categorie();
                c.Id = reader.GetInt32(0);
                c.SubCategorieVan = reader.GetString(1);
                c.Naam = reader.GetString(2);
                categorien.Add(c);
            }
            db.Close();
            return categorien;
        }

我的问题是&#34; categorie_id&#34;中的一些值。列是NULL和&#34; reader.GetString(1)&#34;方法无法处理NULL值。

如何使用我的c#代码处理这些NULL值?

4 个答案:

答案 0 :(得分:3)

您可以使用IsDBNull

Categorie c = new Categorie();
c.Id = reader.GetInt32(0);
c.SubCategorieVan = reader.IsDBNull(1) ? null : reader.GetString(1);
c.Naam = reader.GetString(2);
categorien.Add(c);

答案 1 :(得分:3)

您可以在SQL中使用COALESCE()函数并返回默认值,如

select c.bijdrage_id, 
coalesce(c.categorie_id,0) AS Subcategorievan, 
c.Naam 
from CATEGORIE as c

答案 2 :(得分:1)

问题是,数据库中的null不会返回C#null,而是返回DbNull.Value。如果返回了c#null,则问题将解决所有引用类型(但不是所有值类型)。因此,当数据库中的列可以为空时,您必须检查DbNull.Value

你有几个选择:

  • 使用SqlDataReader.IsDbNull(...)进行测试。
  • 使用as运算符与SqlDataReader.GetValue(...)结合使用进行测试。这仅适用于可空类型。

示例:

c.SubCategorieVan = reader.IsDbNull(1) ? null : reader.GetString(1);

c.SubCategorieVan = reader.GetValue(1) as string;

或者......如果你想给你的属性一个默认值,当返回DbNull时,你可以在你的代码中给出一个默认值:

c.SubCategorieVan = reader.IsDbNull(1) ? "Leeg" : reader.GetString(1);

c.SubCategorieVan = reader.GetValue(1) as string ?? "Leeg";

您可以创建一个扩展方法:

static public T GetValue<T>(this IDataReader reader, int columnIndex, T defaultValue = default(T))
{
    return reader.IsDbNull(columnIndex) ? defaultValue : (T)reader.GetValue(columnIndex)
}

这样,你的阅读方法就会变得美观干净:

c.Id = reader.GetValue<int>(0);
c.SubCategorieVan = reader.GetValue<string>(1, "Leeg"); // In case you want to use this default value.
c.Naam = reader.GetValue<string>(2); 

答案 3 :(得分:0)

扩展方法一切都更好.... 这是我很久以前在互联网上找到的一个小宝石:

public static class IDataReaderExtensions
{
    public static T GetValueOrDefault<T>(this IDataReader reader, int index)
    {
        return (Convert.IsDBNull(reader[index])) ? default(T) : (T)reader.GetValue(index);
    }

    public static T GetValueOrDefault<T>(this IDataReader reader, string name)
    {
        return reader.GetValueOrDefault<T>(reader.GetOrdinal(name));
    }
}

然后你就这样使用它:

c.SubCategorieVan = reader.GetValueOrDefault<int>(1);