automapper指定将一种属性类型映射到另一种属性的规则

时间:2014-11-28 17:22:29

标签: c# automapper

我有一组业务对象需要作为实体持久化。业务对象具有许多TimeSpan类型的属性。我想将它们映射到我的实体上的长属性。

public class BusinessObject
    {
        public string Name { get; set; }
        public TimeSpan ProcessingTime { get; set; }
        public TimeSpan WaitTime { get; set; }
        public TimeSpan RecordTime { get; set; }
    }

    public class Entity
    {
        public string Name { get; set; }
        public long ProcessingTime { get; set; }
        public long WaitTime { get; set; }
        public long RecordTime { get; set; }
    }

    public void CreateMapping()
    {
        Mapper.CreateMap<BusinessObject, Entity>()
            .ForMember(e => e.ProcessingTime, opt => opt.MapFrom(src => src.ProcessingTime.TotalMilliseconds))
            .ForMember(e => e.WaitTime, opt => opt.MapFrom(src => src.WaitTime.TotalMilliseconds))
            .ForMember(e => e.RecordTime, opt => opt.MapFrom(src => src.RecordTime.TotalMilliseconds));
    }

我是否可以在映射中指定所有Timespan属性应该映射到该映射的长度,而不必写出每个属性?

1 个答案:

答案 0 :(得分:0)

看起来您可以覆盖为TypeConverter类型实例化的TimeSpan https://github.com/AutoMapper/AutoMapper/blob/develop/src/AutoMapper/Mappers/TypeConverterMapper.cs