使用AutoMapper将DataTable映射到对象(DTO)
我正在尝试使用AutoMappers DynamicMapfunction将DataTable映射到对象(DTO)。
DataTable dt; dt = new dalAllInvestors().InvestorNameSearch(investorNameSearch); // Look at DynamicMap - Urgent List apiObject = AutoMapper.Mapper.DynamicMap<IDataReader, List>( dt.CreateDataReader()); return apiObject; public class dtoAPISimpleInvestor { public int FirmID { get; set; } public string FirmName { get; set; } public string Type { get; set; } public string Location { get; set; } }
dt
返回10行但是当你看到apiObject时它没有返回任何行,这似乎没有任何意义。 我现在已经看了一段时间,谷歌搜索后看起来我正在做的正确。
正确的列在dt中返回时映射到dtoAPISimpleInvestor
有人能帮帮我吗?
怎么样以下……
AutoMapper简介
public sealed class SimpleInvestorProfile : Profile { // This is the approach starting with version 5 public SimpleInvestorProfile() { IMappingExpression mappingExpression; mappingExpression = CreateMap(); mappingExpression.ForMember(d => d.FirmID, o => o.MapFrom(s => s["FirmID"])); mappingExpression.ForMember(d => d.FirmName, o => o.MapFrom(s => s["FirmName"])); mappingExpression.ForMember(d => d.Type, o => o.MapFrom(s => s["Type"])); mappingExpression.ForMember(d => d.Location, o => o.MapFrom(s => s["Location"])); } // this method is obsolete in version 5 // protected override void Configure() // { // IMappingExpression mappingExpression; // mappingExpression = CreateMap(); // mappingExpression.ForMember(d => d.FirmID, o => o.MapFrom(s => s["FirmID"])); // mappingExpression.ForMember(d => d.FirmName, o => o.MapFrom(s => s["FirmName"])); // mappingExpression.ForMember(d => d.Type, o => o.MapFrom(s => s["Type"])); // mappingExpression.ForMember(d => d.Location, o => o.MapFrom(s => s["Location"])); // return; // } }
注意 :我使用DataRow
类型作为源而不是IDataReader
(更多内容见下文)。
使用配置文件
MapperConfiguration configuration; configuration = new MapperConfiguration(a => {a.AddProfile(new SimpleInvestorProfile());}); IMapper mapper; mapper = configuration.CreateMapper(); List result; result = mapper.Map, List>(rows);
result
对象应包含具有正确数据的正确数量的dtoAPISimpleInvestor
对象。
注意 :对mapper.Map
的调用采用List
类型的对象,该对象可以使用语句new List
从DataTable
对象获取new List
(因为DataTable
对象的Rows
属性是一个实现IEnumerable
而不是IEnumerable
的集合)。
这可能不是唯一的解决方案,但我已经validation它有效。
作为旁注,我注意到您引用的DynamicMap
方法已在最新版本的库中标记为已过时,因此您可能希望避免使用它。
这对我有用:automapper的版本是从nugget 3.1.1下载
using AutoMapper; public List ReadData (DataTable dt) { return Mapper.DynamicMap>(dt.CreateDataReader()); }
这样的调用方法:
DataTable dt = getPeopleDT(); List peopleList = ReadData (dt);