DCSIMG
Extension Methods: IDataReader.GetValue<T> - Gilad Lavian's Blog

Gilad Lavian's Blog

In Development

Extension Methods: IDataReader.GetValue<T>

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");
}

תוכן התגובה

Web Development Community כתב/ה:

You are voted (great) - Trackback from Web Development Community

# December 7, 2008 4:14 AM

DotNetKicks.com כתב/ה:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# December 7, 2008 4:14 AM

Marwan כתב/ה:

Thanks,

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

# December 7, 2008 6:42 AM

Gilad Lavian כתב/ה:

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.

# December 7, 2008 8:11 AM

Yoann. B כתב/ה:

Hi,

Thanks for this article.

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

# December 7, 2008 8:03 PM

Gilad Lavian כתב/ה:

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.

# December 8, 2008 12:16 AM
שלח תגובה

(שדה חובה)  

(שדה חובה)  

(אופציונלי)

(שדה חובה) 

Please add 7 and 8 and type the answer here:


Enter the numbers above: