How can I use a dataset in Automapper?

2019-04-12 11:46发布

问题:

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);