using automapper with .net core to get list of data from IDataReader Edit

Murugan Andezuthu Dharmaratnam | 12 January 2022 | 31

I have been using automapper 3.3.0 to read data from databases using a data reader. In this article, we will explore how to get data from a database to a list of objects using automapper and ado .net data reader. I have seen comments on stackoverflow like it is working fine using basic reflection, I always get an empty list using Automapper, "automapper returning empty list but reflection works fine" etc. Below you can check the working code.


You just need to install AutoMapper.Data using nuget package manager

Check below the working sample code.


public dynamic ReadData<T1>(string connectionString, string queryString)
    List<T1> t1 = null;
    var config = new MapperConfiguration(cfg => {
        cfg.CreateMap<IDataReader, T1>();
    var mapper = new Mapper(config);
    using (var connection = new NpgsqlConnection(connectionString))
    using (var command = new NpgsqlCommand(queryString, connection))
        command.CommandTimeout = 600;
        using (var reader = command.ExecuteReader(CommandBehavior.Default))
            int count = 0;
            bool HasResult = true;
            while (HasResult)
                var readerschema = reader.GetSchemaTable();
                count = count   1;
                switch (count)
                    case 1:
                        t1 = mapper.Map<IDataReader, List<T1>>(reader);
                if (reader.NextResult())
                    HasResult = true;

                    HasResult = false;
    dynamic retval = new ExpandoObject();
    new sgre_dfp_bot.Common().AddProperty(retval, typeof(T1).Name, t1);
    return retval;