【问题标题】:Complex Object mapping using Automapper使用 Automapper 进行复杂对象映射
【发布时间】: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 的使用以及vlaval 的混合使得这非常难读。
  • 抱歉,我已经编辑了 valCollectionList 上的错字

标签: c# asp.net-mvc linq lambda automapper


【解决方案1】:

你很接近,但string.Join 应该在Select 之外(目前它编译只是因为stringIEnumerable&lt;char&gt;,因此达到this overload,结果是一些奇怪的逗号连接的字符串列表字符):

.ForMember(dest => dest.RegistrationNumbers, opt => opt.MapFrom(src =>
    string.Join(", ", src.Vehicles.Select(v => v.RegistrationNumber))));

【讨论】:

  • 非常感谢伊万,感谢您的明确解释,我已将此标记为答案
猜你喜欢
  • 1970-01-01
  • 2012-10-16
  • 2020-04-03
  • 2012-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
相关资源
最近更新 更多