How can I use a dataset in Automapper?

做~自己de王妃 提交于 2019-12-09 18:51:09

问题


I am currently using a datareader as the source but I want to instead use a dataset.

//datareader

AutoMapper.Mapper.CreateMap<IDataReader, AccountDTO>()
             .ForMember(m => m.AccountId, opt => opt.MapFrom (r => r.GetInt32(r.GetOrdinal("AccountId"))))
             .ForMember(m => m.ParentAccountId, opt => opt.MapFrom(r => r.GetInt32(r.GetOrdinal("ParentAccountId"))))
             .ForMember(m => m.IsInactive, opt => opt.MapFrom(r => r.GetString(r.GetOrdinal("IsInactive"))))
             .ForMember(m => m.AccountName, opt => opt.MapFrom(r => r.GetString(r.GetOrdinal("AccountName"))))


//dataset

 AutoMapper.Mapper.CreateMap<DataSet, AccountDTO>()
                 .ForMember(m => m.AccountId, opt => opt.MapFrom(r => r.Tables[0].Columns[Constants.MappingFields.Accounts.AccountId]))
                 .ForMember(m => m.ParentAccountId, opt => opt.MapFrom(r => r.Tables[0].Columns[Constants.MappingFields.Accounts.ParentAccountId]))
                 .ForMember(m => m.IsInactive, opt => opt.MapFrom(r => r.Tables[0].Columns[Constants.MappingFields.Accounts.IsInactive]))
                 .ForMember(m => m.AccountName, opt => opt.MapFrom(r => r.Tables[0].Columns[Constants.MappingFields.Accounts.AccountName]))
                 .ForMember(m => m.AccountNumber, opt => opt.MapFrom(r => r.Tables[0].Columns[Constants.MappingFields.Accounts.AccountNumber]))

any ideas?


回答1:


I want to use the dataset instead of the datareader so I dont keep the connection to the database open.

I think I have found the solution;

  1. Create the dataset and close/dispose the connection
  2. create a datatablereader from the datatable and pass the in

This seems to be working.

 DataTableReader dataTableReader = ds.Tables[0].CreateDataReader();
                conn101.Close();
                conn101.Dispose();


                List<AccountDTO> accountDto1s = Mapper.Map<IDataReader, List<AccountDTO>>(dataTableReader);


来源:https://stackoverflow.com/questions/5180906/how-can-i-use-a-dataset-in-automapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!