Extension Methods: IDataReader.GetValue<T>

17 בנובמבר 2008

תגיות: , , ,
4 תגובות

A convenient solution to get value from IDataReader field.

/// <summary>
/// Gets the reader field value.
/// </summary>
/// <typeparam name="TField">The type of the field.</typeparam>
/// <param name="reader">The reader.</param>
/// <param name="fieldName">Name of the field.</param>
/// <returns></returns>
public static TField GetValue<TField>(this IDataReader reader, string fieldName)
{
    //Guard
    if (string.IsNullOrEmpty(fieldName)) throw new ArgumentException("fieldName");
    return (TField)reader.GetValue(reader.GetOrdinal(fieldName));
}

Usage:

IDataReader reeader = _database.ExecuteReader(command);
if (reader.Read())
{
    int productId = reader.GetValue<int>("ProductId");
}

הוסף תגובה
facebook linkedin twitter email

כתיבת תגובה

האימייל לא יוצג באתר. שדות החובה מסומנים *

4 תגובות

  1. Marwan7 בדצמבר 2008 ב 6:42

    Thanks,
    but what is the difference between this and the Typed Accessor Methods(GetString,GetInt32,GetDouble…)?

    הגב
  2. Gilad Lavian7 בדצמבר 2008 ב 8:11

    This is the methods used when you use reader.GetDouble(int i):
    public override double GetDouble(int i)
    {
    this.ReadColumn(i);
    return this._data[i].Double;
    }

    The _data array is a collection of SqlBuffer.
    When the reader is being populated its try to use the exact type like Double, Int32, Bool.
    In most cases there will be no casting in this method, but sometimes there will be. Note SqlBuufer inherit object so its always a ref type.

    In my extension method, I always use casting.
    The difference is you only need to parse the filedName and not the ordinal index.

    הגב
  3. Yoann. B7 בדצמבר 2008 ב 20:03

    Hi,

    Thanks for this article.

    Here is my approach without using ordinal and manage DBNull values : blog.sb2.fr/…/IDataReader-Extension-Method-GetValue3cT3e.aspx

    הגב
  4. Gilad Lavian8 בדצמבר 2008 ב 0:16

    Hi Yoann, thanks for the replay.
    I think you should considure in your approach that the user should know when the data returns as DBNull and not return as the defaule accessor value.
    Anyway that may approach, just keep the natural code.

    הגב