/// <summary> /// Converts an IDataReader to a single object, using the specified record reader. /// </summary> /// <typeparam name="T">The expected type of the object.</typeparam> /// <param name="reader">The data reader.</param> /// <param name="recordReader">The the record reader to use.</param> /// <returns>A list of objects.</returns> public static T Single <T>(this IDataReader reader, IRecordReader <T> recordReader) { if (reader == null) { throw new ArgumentNullException("reader"); } if (recordReader == null) { throw new ArgumentNullException("recordReader"); } if (reader.IsClosed) { return(default(T)); } // get the mapper var mapper = recordReader.GetRecordReader(reader); try { if (reader.Read()) { return(mapper(reader)); } else { return(default(T)); } } finally { reader.Advance(); } }
/// <inheritdoc/> public override Func <IDataReader, T> GetRecordReader(IDataReader reader) { var baseReader = _baseReader.GetRecordReader(reader); return(r => { using (var wrapped = new CachedDbDataReader(r)) { var t = baseReader(wrapped); return _postRead(wrapped, t); } }); }
/// <summary> /// Converts an IDataReader to an enumerable. The reader is closed after all records are read. /// </summary> /// <typeparam name="T">The type of object to return.</typeparam> /// <param name="reader">The data reader.</param> /// <param name="recordReader">The record reader to use.</param> /// <returns>An enumerable over the return results.</returns> /// <remarks> /// If you use this method and are relying on CommandBehavior.CloseConnection to close the connection, note that if all of the records are not read /// (due to an exception or otherwise), then the connection will leak until GC is run. Your code is responsible for closing the connection. /// </remarks> public static IEnumerable <T> AsEnumerable <T>(this IDataReader reader, IRecordReader <T> recordReader) { // if the reader is closed, then we return an empty list, rather than blowing up if (reader.IsClosed) { yield break; } // get the mapper var mapper = recordReader.GetRecordReader(reader); // read in all of the objects from the reader while (reader.Read()) { yield return(mapper(reader)); } // advance to the next recordset reader.Advance(); }
public Func<IDataReader, TBase> GetRecordReader(IDataReader reader) { var baseReader = _recordReader.GetRecordReader(reader); return r => (TBase)(object)baseReader(r); }