自动映射器,将天数添加到目标日期时间属性

本文关键字:添加 目标 日期 属性 时间 映射 | 更新日期: 2023-09-27 18:36:05

我有一个场景,我试图将源对象中的整数值映射到DateTime属性。你自然不能那样做。但我想做的是将源中整数中的天数添加到目标属性的DateTime属性值中。

到目前为止,我还没有找到解释这种情况的解决方案。

有人知道该怎么做吗?

伪代码示例:

Mapper.CreateMap<EditAdView, Ad>()
         .ForMember(dest => dest.ExpirationDate, opt => opt.MapFrom(src => dest.ExpirationDate.AddDays(src.ExtendedDurationInWeeks * 7)); 

上面的例子不起作用,但它确实显示了我想做什么。 即向目标属性对象的现有值添加天数

请记住dest.ExpirationDate 属性已经填充了一个值,这就是为什么我需要从我的源对象更新它。

提前谢谢。

解决方案:(详见下面的答案)

       //in the mapping configuration
       Mapper.CreateMap<EditAdView, Ad>()
              .ForMember(dest => dest.ExpirationDate, opt => opt.Ignore())
              .AfterMap((src, dest) => dest.ExpirationDate = dest.ExpirationDate.AddDays(src.ExtendedDuretionInWeeks * 7));
       //in the controller
       existingAd = Mapper.Map(view, existingAd);

自动映射器,将天数添加到目标日期时间属性

我认为这将满足您的需求:

public class Source
{
    public int ExtendedDurationInWeeks { get; set; }
}    
public class Destination
{
    public DateTime ExpirationDate { get; set; }
    public Destination()
    {
        ExpirationDate = DateTime.Now.Date;
    }
}
var source = new Source{ ExtendedDurationInWeeks = 2 };
var destination = new Destination {ExpirationDate = DateTime.Now.Date};
Mapper.CreateMap<Source, Destination>()
      .AfterMap((s,d) => d.ExpirationDate = 
                        d.ExpirationDate.AddDays(s.ExtendedDurationInWeeks * 7));
destination = Mapper.Map(source, destination);