映射时AutoMapper.Data错误

时间:2017-02-15 08:35:27

标签: c# sql-server automapper idatareader automapper-4

我正在使用automapper v4.1.1和automapper.data1.0.0.beta 1.我有控制台应用程序,我的映射代码如下:

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

            cfg.CreateMap<IDataRecord, AircraftDetails>();

        });

我的db调用代码和映射看起来像

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;

当我运行此代码时,我收到错误:

  

未处理的异常:System.InvalidCastException:指定的强制转换无效。      在DynamicCreate(IDataRecord)      在AutoMapper.Data.DataReaderMapper.d__10.MoveNext()      在System.Linq.Enumerable.d__94 1.MoveNext() at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable 1来源)

任何想法我做错了什么?

干杯

伊斯梅尔

1 个答案:

答案 0 :(得分:0)

不确定,但您可能应该为IDataRecord创建映射,但对于IDataReader:

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

基于this question