AutoMapper with a list data from IDataReader

vNext picture vNext · Jul 29, 2011 · Viewed 11k times · Source
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?

Answer

Dave Walker picture Dave Walker · Jul 29, 2011

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;
    }