7

I went through How can I easily convert DataReader to List<T>?

I wanted to implement something like what is accepted as an answer in the above link.

Scenrio:

I am using OdbcDataReader to retrieve from the database.

And I have a Model Class . FYI , the properties of this class are exact replica of the column names from the database. I need to map these columns to the properties and return List Can this be accomplished using Automapper.

Community
  • 1
  • 1
Vikram
  • 181
  • 1
  • 3
  • 14
  • Why can't you use the solution provided in that answer? It looks like it doesn't depend on a specific data reader implementation. – Dirk Sep 05 '14 at 08:01
  • Just noting that in AutoMapper 1.1 - the last version for .Net 3.5 - **DataReader mappings are case sensitive**. To use this version in a case-insensitive manner AutoMapper needs patching as in https://github.com/AutoMapper/AutoMapper/issues/90 – stuartd Sep 05 '14 at 15:13

1 Answers1

13

Something like this

public List<T> ReadData<T>(string queryString)
{
    using (var connection = new SqlConnection(constr))
        using (var command = new SqlCommand(queryString, connection))
        {
            connection.Open();
            using (var reader = command.ExecuteReader())
                if (reader.HasRows)
                    return Mapper.DynamicMap<IDataReader, List<T>>(reader);
        }

    return null;
}

Define your class

public class MarkType
{
    public int id { get; set; }
    public string name { get; set; }
    public DateTime inserted { get; set; }
}

Use

List<MarkType> lst = _helper.ReadData<MarkType>("SELECT [id],[name],[inserted] FROM [marktype]");
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
slava
  • 1,901
  • 6
  • 28
  • 32
  • Thanks all for your valuable inputs – Vikram Sep 08 '14 at 01:00
  • 8
    For anyone that refers to this after Dec 29, 2014, the Automapper project has removed support for `IDataReader` in Automapper versions 4.0 and higher. Refer to this [commit](https://github.com/AutoMapper/AutoMapper/commit/33831e3b53ed1cd698558daa2db483906ec5c13a). Version 3.1.1 (available on NuGet) still has this functionality. – Cameron Nov 13 '15 at 20:16
  • 6
    There is a [nuget package](https://www.nuget.org/packages/AutoMapper.Data) that adds this back in (currently it is in beta). [GitHub AutoMapper.Data](https://github.com/AutoMapper/AutoMapper.Data) – jhamm Dec 01 '15 at 22:30