C# 使用Automapper的复杂对象映射
我正在尝试使用自动映射器来实现下面的代码C# 使用Automapper的复杂对象映射,c#,asp.net-mvc,linq,lambda,automapper,C#,Asp.net Mvc,Linq,Lambda,Automapper,我正在尝试使用自动映射器来实现下面的代码 List<VlaListView> vlaVmList = new List<VlaListView>(); var vlaCollectionList = vlaCollection.ToList(); //database populate list foreach (var vla in vlaCollectionList) { VlaListView vlaVm = new VlaListView();
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);
}
非常感谢您提供的任何帮助。很接近,但是
string.Join
应该在Select
之外(目前它编译的唯一原因是string
是IEnumerable
,因此命中,结果是一些奇怪的字符串列表,带有逗号连接字符):
HGNNOTATION的使用以及
vla
和val
的混合使得这一点非常难以理解。很抱歉,我编辑了ValCollectionList上的打字错误非常感谢Ivan,感谢您的明确解释,我将此标记为答案
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))));
});
.ForMember(dest => dest.RegistrationNumbers, opt => opt.MapFrom(src =>
string.Join(", ", src.Vehicles.Select(v => v.RegistrationNumber))));