2
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?

raym0nd
  • 3,172
  • 7
  • 36
  • 73
vNext
  • 1,102
  • 4
  • 16
  • 28

2 Answers2

8

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;
    }
Dave Walker
  • 3,498
  • 1
  • 24
  • 25
  • thank, you're but... AutoMapper.Mapper.CreateMap>(); or AutoMapper.Mapper.CreateMap(); is right? I see both of them work okey! – vNext Jul 30 '11 at 16:42
  • 1
    I always prefer to be more explicit so IList. It probably does some magic so that it doesn't matter internally. – Dave Walker Jul 30 '11 at 21:01
  • 1
    It throws an error saying it doesn't like `IList`. And It returns empty list to me, when i specify `List` instead of `IList`. – AgentFire May 08 '19 at 22:48
-4

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());
Rama Krishna
  • 300
  • 2
  • 4