I am looking for a way to get AutoMapperto indicate DateTimeKindon all my dates before Utcwhen using ProjectTo. I looked around and found some solutions, but no one works:
cfg.CreateMap<DateTime, DateTime>().ConvertUsing(i => DateTime.SpecifyKind(i, DateTimeKind.Utc));
cfg.CreateMap<DateTime?, DateTime?>().ConvertUsing(i => DateTime.SpecifyKind(i.Value, DateTimeKind.Utc));
or
cfg.CreateMap<DateTime, DateTime>().ProjectUsing(i => new DateTime(i.Year, i.Month, i.Day, i.Hour, i.Minute, i.Second, DateTimeKind.Utc));
cfg.CreateMap<DateTime?, DateTime?>().ProjectUsing(i => new DateTime(i.Value.Year, i.Value.Month, i.Value.Day, i.Value.Hour, i.Value.Minute, i.Value.Second, DateTimeKind.Utc));
or
cfg.CreateMap<DateTime, DateTime>().ConstructProjectionUsing(i => new DateTime(i.Year, i.Month, i.Day, i.Hour, i.Minute, i.Second, DateTimeKind.Utc));
cfg.CreateMap<DateTime?, DateTime?>().ConstructProjectionUsing(i => new DateTime(i.Value.Year, i.Value.Month, i.Value.Day, i.Value.Hour, i.Value.Minute, i.Value.Second, DateTimeKind.Utc));
I also tried this, but after some digging in the docs it seems that ResolveUsing will not work when using ProjectTo
cfg.ForAllPropertyMaps(map => (map.SourceType == typeof(DateTime?) || map.SourceType == typeof(DateTime)), (map, expression) =>
{
expression.ResolveUsing(o =>
{
var date = o as DateTime;
DateTime.SpecifyKind(date, DateTimeKind.Utc);
return date;
});
});
Am I doing it wrong or is this the best way to try to achieve this?