Reputation: 13
I'm trying to use auto mapper to achieve the below code.
List<VlaListView> vlaVmList = new List<VlaListView>();
var vlaCollectionList = vlaCollection.ToList(); //database populate list
foreach (var vla in vlaCollectionList)
{
VlaListView vlaVm = new VlaListView();
vlaVm.VlaId = vla.VlaId;
vlaVm.UserName = vla.UserName;
vlaVm.DateOut = vla.DateOut.ToShortDateString();
vlaVm.ReturnDate = vla.ReturnDate.ToShortDateString();
vlaVm.Status = vla.Status;
string regnumbers = string.Empty;
foreach (var vehicle in vla.Vehicles)
{
regnumbers += vehicle.RegistrationNumber + ", ";
}
regnumbers = regnumbers.Remove(regnumbers.Length - 2);
vlaVm.RegistrationNumbers = regnumbers;
vlaVmList.Add(vlaVm);
}
I get all the values to map apart from the registration numbers which can have a list of vehicles with registration numbers. I'm trying to loop and get the values of vla.vehicles.RegistrationNumber
, concatenate and save the results to my view model field. My Automapper code is below
AutoMapper.Mapper.Initialize(config =>
{
config.CreateMap<Vla, VlaListView>()
.ForMember(x => x.DateOut, opt => opt.MapFrom(src => src.DateOut.ToShortDateString()))
.ForMember(x => x.ReturnDate, opt => opt.MapFrom(src => src.ReturnDate.ToShortDateString()))
// this is the ForMember I can't work out, I can't get the values of the registration numbers
.ForMember(x => x.RegistrationNumbers, opt => opt.MapFrom(src => src.Vehicles.Select(v => string.Join(", ", v.RegistrationNumber))));
});
Any help with this would be much appreciated.
Upvotes: 1
Views: 216
Reputation: 205629
You are close, but string.Join
should be outside the Select
(currently it compiles only because string
is IEnumerable<char>
, thus hitting this overload, and the results is some strange list of strings with comma concatenated chars):
.ForMember(dest => dest.RegistrationNumbers, opt => opt.MapFrom(src =>
string.Join(", ", src.Vehicles.Select(v => v.RegistrationNumber))));
Upvotes: 1