简体   繁体   English

自动映像,向目标DateTime属性添加天数

[英]Automapper, add number of days to destination DateTime property

I'm have a scenario where I am trying to map an integer value in my source object to a DateTime property. 我有一个场景,我试图将源对象中的整数值映射到DateTime属性。 Naturally you can't do that. 当然你不能这样做。 But what I want to do is add the amount of days in the integer in my source, to the DateTime property value of my destination property. 但我想要做的是将源中整数的天数添加到目标属性的DateTime属性值。

I haven't been able to find a solution so far that explains this scenario. 到目前为止,我还没能找到解释这种情况的解决方案。

Anyone know how to do that ? 谁知道怎么做?

Pseudo code example: 伪代码示例:

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

The above example doesn't work, but it does show what I want to do. 上面的示例不起作用,但它确实显示了我想要做的事情。 Namely add an amount of days to the existing value of the destination property object 即向目标属性对象的现有值添加天数

Keep in mind : the dest.ExpirationDate property is already populated with a value, which is why I need to update it from my source object. 请记住dest.ExpirationDate属性已经填充了一个值,这就是我需要从源对象更新它的原因。

Thanks in advance. 提前致谢。

Solution: (see below answer for details) 解决方案:(详见下方答案)

       //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);

I think this will do what you're looking for: 我想这会做你想要的:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM