【发布时间】:2017-06-28 08:51:45
【问题描述】:
我正在尝试使用自动映射器来实现以下代码。
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))));
});
对此的任何帮助将不胜感激。
【问题讨论】:
-
hngnNotation 的使用以及
vla和val的混合使得这非常难读。 -
抱歉,我已经编辑了 valCollectionList 上的错字
标签: c# asp.net-mvc linq lambda automapper