AutoMapper and IDataReader



我想将数据从IDateReader映射到某个类,但不能简单地做到这一点。 我写了以下代码:

 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:我尝试使用来自Nuget的Automapper.Data,但它取决于NETStandard.library,但我使用.NET Framework 4.5但是这种方式对我不利,因为我必须描述每列的映射规则。是否有可能避免描述所有这些规则?

您可以使用 ITypeConverter ,如下所示:

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>());

最新更新