Simple IDataReader ORM extension methods

Instead of deploying an entire ORM solution and because I’m lazy, I created (read: google-distilled) these simple extension methods to map an IDataReader into a IEnumerable<T>. So basically, I can map any result set (that is an IDataReader) into a list of strongly typed objects of my choosing.

For example, to convert my IDataReader object containing account information into an IEnumerable set of “Account” objects, I’d do this:

        public virtual IEnumerable<Account> GetAccountBalances(User user)
            return DataAccess.GetFundBalances(user.Id) // Returns an IDataReader
                    .MapTo(x => new Account()
                        // "x" is a IDataRecord object
                        Id = x["id"].ToString(),
                        Type = x["type"].ToString(),
                        PlanType = x["plantype"].ToString(),
                        PlanDescription = x["plandescription"].ToString(),
                        Balance = x["balance"]


The “MapTo” extension method accepts the delegate “CreateObjectFromDataRecord” which can be passed in with a lambda expression to neatly create the strongly typed object from the row of data (IDataRecord) inline.

Here’s the code for the extension methods:

    public static class DataReaderExtensions
        public delegate T CreateObjectFromDataRecord<T>(IDataRecord record);

        public static IEnumerable<T> MapTo<T>(this IDataReader reader, CreateObjectFromDataRecord<T> createobj)
            var targets = new List<T>();
            while (reader.Read())

            return targets;

        public static T MapFirstTo<T>(this IDataReader reader, CreateObjectFromDataRecord<T> createobj)
            T target = default(T);

            if (reader.Read())
                target = createobj(reader);

            return target;

About Paul Martin

I enjoy rock climbing, playing guitar, writing code...
This entry was posted in .NET, C#, extension methods, IDataReader, ORM. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s