Automapper 8.0+ 将所有日期时间转换为 utc

5 c# automapper

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

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# }); }); 
Run Code Online (Sandbox Code Playgroud)

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

Pro*_*man 7

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

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

检查以下示例代码:

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}");            
    }  
}
Run Code Online (Sandbox Code Playgroud)

这将生成以下输出:

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