AutoMapper.Data error when mapping

1.7k Views Asked by At

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

1

There are 1 best solutions below

3
On

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

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

Based on this question