AutoMapper with a list data from IDataReader

风格不统一 提交于 2019-12-22 17:54:15

问题


using (IDataReader dr = DatabaseContext.ExecuteReader(command))
        {
            if (dr.Read())
            {
                AutoMapper.Mapper.CreateMap<IDataReader, ProductModel>();
                return AutoMapper.Mapper.Map<IDataReader, IList<ProductModel>>(dr);
            }
            return null;
        }

if dr has only one row -> error: threw an exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException'

if dr has more than one row, it run ok.

any help?


回答1:


The problem is that Automapper is calling Read() as well - so is trying to always look at the second record onwards. If you think about it if you have 1000 rows in the reader - how is AutoMapper going to convert that to a list without iterating through them all calling Read()?

Change your line to call HasRows

e.g.

using (IDataReader dr = DatabaseContext.ExecuteReader(command))
    {
        if (dr.HasRows)
        {
            AutoMapper.Mapper.CreateMap<IDataReader, ProductModel>();
            return AutoMapper.Mapper.Map<IDataReader, IList<ProductModel>>(dr);
        }

        return null;
    }



回答2:


Add AutoMapper.Net4 and add the mappers ahead of CreateMap as below:

    MapperRegistry.Mappers.Add(new DataReaderMapper());
    MapperRegistry.Mappers.Add(new NameValueCollectionMapper());
    MapperRegistry.Mappers.Add(new HashSetMapper());
    MapperRegistry.Mappers.Add(new ListSourceMapper());
    MapperRegistry.Mappers.Add(new TypeConverterMapper());


来源:https://stackoverflow.com/questions/6873822/automapper-with-a-list-data-from-idatareader

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!