DataReader best-practices

后端 未结 2 2030
轮回少年
轮回少年 2020-12-09 12:35

Similar to this question, but the answers never really got around to what I want to know. Is there any standards around getting values from a DataReader? I.e., is this

相关标签:
2条回答
  • 2020-12-09 13:08

    Here is the way that I do it:

    Int32 ordinal = dataReader.GetOrdinal("ColumnName");
    
    if (!dataReader.IsDBNull(ordinal))
        yourString = dataReader.GetString(ordinal);
    

    It is important to check for DBNull like I have shown above because if the field is null in the DataReader it will throw an exception when you try to retrieve it.

    0 讨论(0)
  • 2020-12-09 13:12

    I made some extension methods to let me treat an IDataReader as an enumerable, and to deal with DbNull by returning nullable ints, etc. This lets me check for null and apply a default value with the C# ?? operator.

    /// <summary>
    /// Returns an IEnumerable view of the data reader.
    /// WARNING: Does not support readers with multiple result sets.
    /// The reader will be closed after the first result set is read.
    /// </summary>
    public static IEnumerable<IDataRecord> AsEnumerable(this IDataReader reader)
    {
        if (reader == null)
            throw new ArgumentNullException("reader");
    
        using (reader)
        {
            while (reader.Read())
            {
                yield return reader;
            }
        }
    }
    
    public static int? GetNullableInt32(this IDataRecord dr, string fieldName)
    {
        return GetNullableInt32(dr, dr.GetOrdinal(fieldName));
    }
    
    public static int? GetNullableInt32(this IDataRecord dr, int ordinal)
    {
        return dr.IsDBNull(ordinal) ? null : (int?)dr.GetInt32(ordinal);
    }
    

    ...and so on for the other GetDataType() methods on IDataReader.

    0 讨论(0)
提交回复
热议问题