使用IDataReader的Automapper自定义映射

时间:2018-08-29 09:37:32

标签: c# .net automapper idatareader

我正在尝试使用AutoMapper将DataTable映射到DtoObject。仅当我尝试为未映射的特定字段添加一些自定义映射时,此方法才完美。

使用nuget包:

  • AutoMapper
  • AutoMapper.Data

设置(统一使用):

container.RegisterInstance<IMapper>(new AutoMapperConfiguration().Configure().CreateMapper());

public class AutoMapperBootstrap : Profile
{
    public AutoMapperBootstrap()
    {
        CreateMap<IDataReader, DtoObject>()
            .ForMember(dest => dest.SomeField, opt => opt.MapFrom(src => src.GetDateTime(0)));
    }
}


public class AutoMapperConfiguration
{
    public MapperConfiguration Configure()
    {
        var config = new MapperConfiguration(cfg =>
        {
            cfg.AddDataReaderMapping();
            cfg.AddProfile<AutoMapperBootstrap>();
        });
        return config;
    }
}

映射:

private IEnumerable<DtoObject> DataTableReintegratieGegevensToIEnumerable(DataTable dt)
{
    return _mapper.Map<IDataReader, IEnumerable<DtoObject>>(dt.CreateDataReader());
}

对象:

public class DtoObject
{
    public DateTime? SomeField { get; set; }
    ...
}

SomeField外,所有字段均已正确映射。有任何想法吗?

0 个答案:

没有答案