Automapper 8.0+ 所有日期时间到 utc

Automapper 8.0+ all datetime to utc

我想通过为 Automapper 8.0 的所有属性的映射添加类型到日期时间,将所有属性从日期时间未指定类型映射到 UTC 类型,我发现了一些可能有效的解决方案,但它们适用于旧版本的 Automapper使用 ResolveUsing 而不是 MapFrom()。 如何实现?

cfg.ForAllPropertyMaps(map => map.TypeMap.SourceType is IDbType && (map.SourceType == typeof(DateTime?) || map.SourceType == typeof(DateTime)), (map, expression) => { expression.ResolveUsing(o => { return #DO_WHATEVER_YOU_NEED# }); }); 

我只想映射来自服务器-> 客户端的所有实体和日期时间以添加 Utc Kind,以上代码来自 github。com/AutoMapper/AutoMapper/issues/1650

您可以使用 ConvertUsing() 作为 DateTime 类型的 CreateMap() 条目。代码可能如下所示:

cfg.CreateMap<DateTime, DateTime>().ConvertUsing((s, d) => {
    return DateTime.SpecifyKind(s, DateTimeKind.Utc);
});

检查以下示例代码:

class TestDTO {
    public DateTime SomeProp {get; set;}
}

class Program
{
    static void Main(string[] args)
    {
        var config = new MapperConfiguration(cfg => {
            cfg.CreateMap<TestDTO, TestDTO>();
            cfg.CreateMap<DateTime, DateTime>().ConvertUsing((s, d) => {
                return DateTime.SpecifyKind(s, DateTimeKind.Utc);
            });
        });
        TestDTO dto = new TestDTO {
            SomeProp = DateTime.Today
        };
        var mapper = new Mapper(config);
        DateTime now = dto.SomeProp;
        Console.WriteLine($"{now} - {now.Kind}");
        TestDTO changed = mapper.Map<TestDTO>(dto);
        DateTime nowWithKind = changed.SomeProp;
        Console.WriteLine($"{nowWithKind} - {nowWithKind.Kind}");            
    }  
}

这将生成以下输出:

6/16/2020 12:00:00 AM - Local
6/16/2020 12:00:00 AM - Utc