SqlDataReader Best way to check for null values -sqlDataReader.IsDBNull vs DBNull.Value

前端 未结 3 486
盖世英雄少女心
盖世英雄少女心 2021-02-04 10:01

I want to retrieve decimal values from the database and I would like to know which is the recommended way to check for null values.

I have seen on MSDN - DBNull.Value F

3条回答
  •  迷失自我
    2021-02-04 10:49

    If you want to check for null and handle it (as opposed to checking for null and alerting the program that it was null) you can use the as operator with the null-coalescing operator ??. So in my program

    SqlDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        response.Employees.Add(new Employee() { Id = dr["id"] as int? ?? default(int), ImageUrl = dr["Photo"] as string, JobTitle = dr["JobTitle"] as string });
    }
    

提交回复
热议问题