Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension Method for SqlDataReader?

We have run a conversion tool on an old project which came from VB6.

We're substituting OLEDB with Ado.Net, and RecordSets with SqlDataReaders.

But the converted code always does a rs.Fields['FirstName'] reference, which I guess would be rs['FirstName'] with the database reader (where rs is now q SqlDataReader.

Instead of going through all the code, is there a way I could create an extension method on SqlDataReader, which would then make use of "Fields['FieldName']"?

This is my current attempt:

public static class SqlUtils
    {
        public static object Fields(this SqlDataReader dataReader, string fieldname)
        {
            return dataReader[fieldname];
        }
    }

However, this works with:

Console.WriteLine(reader.Fields("First").ToString());

I need to handle:

Console.WriteLine(reader.Fields["First"].ToString());

Note, [], not ().

like image 279
Craig Avatar asked Nov 23 '25 07:11

Craig


2 Answers

Extension methods are actually just static methods. Since there is no 'static indexer' you cannot have an extension method that uses indexer syntax.

like image 161
Jakub Konecki Avatar answered Nov 24 '25 19:11

Jakub Konecki


this static indexer works just dandy...

public static string GetDRItem(this IDataReader dr, string colName)
{
    return dr[colName].ToString();
}
like image 37
Bohemian Avatar answered Nov 24 '25 20:11

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!