将几个属性从ViewModel映射到对象列表

时间:2019-05-17 16:16:30

标签: c# automapper

我的客户ViewModel如下

public class CustomerViewModel
{
   // Various other properties removed for brevity

    public int DiscountRate { get; set; };

    public DateTime DiscountFromDate { get; set; }

    public DateTime DiscountToDate { get; set; };
 }

我要映射到以下域对象

public class Customer
{
   // Other properties removed for brevity
   public IEnumerable<SettlementDiscount> SettlementDiscounts { get; set; }
}

public class SettlementDiscount
{
    public int CustomerId { get; set; }

    public int DiscountRate { get; set; }

    public DateTime FromDate { get; set; }

    public DateTime ToDate { get; set; }
}

我该如何使用AutoMapper从视图模型映射到域对象再返回?

这样做的原因是,最初,我们只允许为客户创建一个折扣,但是将来,它将更改为允许在不同的日期范围内应用许多折扣。

我正试图避免构建UI来允许多次打折,以节省时间,因为它尚不需要,但是在需要允许多次打折时,已经将后端结构放在适当的位置。我希望客户域对象包含SettlementDiscount对象的列表,该对象目前仅包含一个项目。

到目前为止我尝试过的映射是

CreateMap<Customer, CustomerViewModel>()
   .ForMember(dest => dest.DiscountRate, opt => opt.MapFrom(src => src.SettlementDiscounts.FirstOrDefault().DiscountRate))
   .ForMember(dest => dest.DiscountFromDate, opt => opt.MapFrom(src => src.SettlementDiscounts.FirstOrDefault().FromDate))
   .ForMember(dest => dest.DiscountToDate, opt => opt.MapFrom(src => src.SettlementDiscounts.FirstOrDefault().ToDate))
   .ReverseMap()
   .ForMember(dest => dest.SettlementDiscounts.FirstOrDefault().DiscountRate, opt => opt.MapFrom(src => src.DiscountRate))
   .ForMember(dest => dest.SettlementDiscounts.FirstOrDefault().FromDate, opt => opt.MapFrom(src => src.DiscountFromDate))
   .ForMember(dest => dest.SettlementDiscounts.FirstOrDefault().ToDate, opt => opt.MapFrom(src => src.DiscountToDate));

0 个答案:

没有答案