使用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.Rows.OfType());DataTable对象获取new List(dataTable.Rows.OfType()); (因为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);