s

Introduction

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

author
Murugan Andezuthu Dharmaratnam | calendar 12 January 2022 | 1945

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.

Solution

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>();
        cfg.AddDataReaderMapping();
    }
    );
    var mapper = new Mapper(config);
    using (var connection = new NpgsqlConnection(connectionString))
    using (var command = new NpgsqlCommand(queryString, connection))
    {
        command.CommandTimeout = 600;
        connection.Open();
        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);
                        break;
                }
                if (reader.NextResult())
                {
                    HasResult = true;
                }
                else
                {

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