Automapper 8.0+ all datetime to utc

Viewed 1530

I would like to map all properties from datetime unspecified kind to UTC kind by just adding kind to datetime for mappings for all properties for Automapper 8.0, i found some maybe working solutions, but they are for older versions of Automapper that use ResolveUsing instead of MapFrom(). How to achieve that?

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

I want to map only all entities and Datetimes from server-> client to have Utc Kind added, above code is from github.com/AutoMapper/AutoMapper/issues/1650

1 Answers

You can use ConvertUsing() for a CreateMap() entry for the DateTime type. The code might look like this:

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

Check the following example code:

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

This will generate the following output:

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