Automapper does not map from IDataReader to string correctly

343 Views Asked by At

I am using automapper to map from IDataReader. As long as I used it to map from IDataReader to DTOs there was no problem, but after I added a mapping for string, it doesn't work as expected. Take a look at the following sample code I wrote to demonstrate the problem:

static void Main(string[] args)
{
    var configuration = new MapperConfiguration(cfg =>
    {
        //Here Group is one of my DTOs
        cfg.CreateMap<IDataReader, Group>()
            .ForMember(dest => dest.Id, options => options.MapFrom(src => src["Id"]))
            .ForMember(dest => dest.Name, options => options.MapFrom(src => src["Name"]));

        //This is the mapping for string type, if I remove it the outcome will not change, 
        //it seems automapper does not even see this mapping
        cfg.CreateMap<IDataReader, string>()
            .ConvertUsing(src => src.GetString(0));

    });
    var mapper = configuration.CreateMapper();

    using (SqlConnection connection = new SqlConnection("Data Source=MICHAEL-PC;Initial Catalog=RollingStonesDB;User ID=admin;Password=admin"))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand("GetSaltByLogin 'jt'", connection))
        using (IDataReader reader = command.ExecuteReader())
        {
            if (reader.Read())
            {
                //here instead of giving me the expected result it gives me "System.Data.SqlClient.SqlDataReader"
                string value = mapper.Map<string>(reader);
            }
        }
    }
}

In this line string value = mapper.Map<string>(reader); I expect to get the actual string value of the first column from the IDataReader, instead I get "System.Data.SqlClient.SqlDataReader". Now the really weird thing is that when I remove this line .ForMember(dest => dest.Name, options => options.MapFrom(src => src["Name"])); from the code above, the mapping will work as expected. For me it seems as if this is a bug. How can elegantly fix this issue so that I will have the mapping for my DTOs and string?

0

There are 0 best solutions below