我正在尝试使用自动映射器来实现以下代码。
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);
}
我得到的所有值都要与注册号码分开,注册号码可以包含带注册号码的车辆列表。我正在尝试循环并获取vla.vehicles.RegistrationNumber
的值,连接并将结果保存到我的视图模型字段。我的Automapper代码位于
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))));
});
非常感谢任何帮助。
答案 0 :(得分:1)
您已经离我很近,但string.Join
应该在Select
之外(目前仅在string
为IEnumerable<char>
时进行编译,因此会点击this overload,结果是一些奇怪的字符串列表与逗号连接字符):
.ForMember(dest => dest.RegistrationNumbers, opt => opt.MapFrom(src =>
string.Join(", ", src.Vehicles.Select(v => v.RegistrationNumber))));