1

I am using automapper v4.1.1 and automapper.data1.0.0.beta 1. I have console app and my mapping code looks like:

Mapper.Initialize(cfg => {
            MapperRegistry.Mappers.Add(new DataReaderMapper {YieldReturnEnabled = true}
            );

            cfg.CreateMap<IDataRecord, AircraftDetails>();

        });

And my db call code and mapping looks like

var aircraft=new AircraftDetails();         
        using (SqlConnection connection =
               new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[_connectionString].ConnectionString))
        {
            SqlCommand command =
                new SqlCommand(storedProcedureAsString, connection);


            command.AddInputParameters(new {a=aircraftId});

            connection.Open();

            SqlDataReader reader = command.ExecuteReader();
            if (reader.HasRows)
            {

               var res = Mapper.Map<IDataReader, IEnumerable<AircraftDetails>>(reader);

                aircraft = res.FirstOrDefault();
            }

        }

        return aircraft;

When i run this code i get error:

Unhandled Exception: System.InvalidCastException: Specified cast is not valid. at DynamicCreate(IDataRecord ) at AutoMapper.Data.DataReaderMapper.d__10.MoveNext() at System.Linq.Enumerable.d__941.MoveNext() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source)

Any ideas what I am doing wrong?

Cheers

Ismail

Ismail
  • 923
  • 2
  • 12
  • 29

1 Answers1

0

Not sure, but may be you should create mapping not for IDataRecord, but for IDataReader:

cfg.CreateMap<IDataReader, IEnumerable<AircraftDetails>>();

Based on this question

Community
  • 1
  • 1
viktor.kudria
  • 229
  • 2
  • 14
  • 1
    Hi kudrya, tried that no joy. I just followed example in automapper.data test and thats how its done see https://github.com/AutoMapper/AutoMapper.Data/blob/master/AutoMapper.Data.Tests/DataReaderMapping.cs test When_mapping_a_data_reader_to_a_dto so mapping is IDataRecord but in map IDataReader kind of makes sense as a read on IDataReader gives you IDataRecord. – Ismail Feb 15 '17 at 10:19
  • Hm, and what about `cfg.AddMemberConfiguration().AddMember();` in your configuration section? – viktor.kudria Feb 15 '17 at 10:30
  • kudrya, not tried that as i then decided to use something else as i am pressed for time so i went with https://github.com/sixeyed/projects/tree/master/Sixeyed.Mapping which works. I may try and revisit if i get time. Many thanks for you help. – Ismail Feb 15 '17 at 10:38