Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using AutoMapper with Data Reader

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.

like image 334
Vikram Avatar asked Sep 05 '14 07:09

Vikram


People also ask

When should you not use AutoMapper?

If you have to do complex mapping behavior, it might be better to avoid using AutoMapper for that scenario. Reverse mapping can get very complicated very quickly, and unless it's very simple, you can have business logic showing up in mapping configuration.

Is AutoMapper faster than manual mapping?

Inside this article, it discusses performance and it indicates that Automapper is 7 times slower than manual mapping. This test was done on 100,000 records and I must say I was shocked.


1 Answers

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]");
like image 104
slava Avatar answered Sep 18 '22 16:09

slava