我想将数据从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 Framework4.5,但是这种方式对我不利,因为我必须描述每一列的映射规则。是否有可能避免描述所有这些规则?
发布于 2018-01-10 13:27:13
您可以使用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>());https://stackoverflow.com/questions/48188280
复制相似问题