1

I would like to map data from IDateReader to some class but can not do it simply. I wrote the following code:

 cfg.CreateMap<IDataReader, MyDto>()
      .ForMember(x => x.Id, opt => opt.MapFrom(rdr => rdr["Id"]))
      .ForMember(x => x.Name, opt => opt.MapFrom(rdr => rdr["Name"]))
      .ForMember(x => x.Text, opt => opt.MapFrom(rdr => rdr["Text"]));

UPD: I tried to use Automapper.Data from Nuget but it depends on NETStandard.Library but I use .NET Framework 4.5 But this way is bad for me because I have to describe mapping rule for each column. Is it possible to avoid describing all of these rules?

Pupkin
  • 1,211
  • 3
  • 13
  • 30

1 Answers1

1

You could use an ITypeConverter, such as the following:

public class DataReaderConverter<TDto> : ITypeConverter<IDataReader, TDto> where TDto : new
{
    public TDto Convert(IDataReader source, TDto destination, ResolutionContext context)
    {
        if (destination == null)
        {
            destination = new TDto();
        }

        typeof(TDto).GetProperties()
            .ToList()
            .ForEach(property => property.SetValue(destination, source[property.Name]));
    }
}


cfg.CreateMap<IDataReader, MyDto>().ConvertUsing(new DataReaderConverter<MyDto>());
Aaron M. Eshbach
  • 6,380
  • 12
  • 22