You can find code for adapting a DataRow to the IDataRecord interface all over the place. One scenario in which this might be useful is [when the dregs of coding society are forced to perform] mapping the results of a database call to a custom object with the results sometimes coming back as a DataSet and sometimes as a DataReader.
IDataRecord has a lot of members that you probably wouldn’t use, simply because they are for retrieving strongly-typed values from the record based on numeric index. You’re probably doing these conversions manually and getting the values by named index. If that’s the case, why not constrain the consumption of these types with the following interface:
public interface IIndexedDataRecord { object this[string name] { get; } }
and these adapters:
public class DataReaderAdapter : IIndexedDataRecord { private readonly IDataReader reader; public DataReaderAdapter(IDataReader reader) { this.reader = reader; } public object this[string name] { get { return reader[name]; } } } public class DataRowAdapter : IIndexedDataRecord { private readonly DataRow row; public DataRowAdapter(DataRow row) { this.row = row; } public object this[string name] { get { return row[name]; } } }
I think if I were designing a data layer that used plain ADO.NET (which I would never do), I would use this simplified interface. Of course, the drawback is there would be a need to adapt both IDataReaders and DataRows when passing them to consuming methods, whereas only DataRows would need to be adapted when consuming methods are programmed to the IDataRecord interface.
Comments