强制Automapper使用Project在所有DateTimes上设置DateTimeKind.Utc

时间:2017-03-27 10:48:07

标签: c# automapper

我正在寻找一种方法让AutoMapper在使用DateTimeKind时将Utc指定在ProjectTo的所有日期。我环顾四周并找到了一些解决方案但似乎没有解决方案:

cfg.CreateMap<DateTime, DateTime>().ConvertUsing(i => DateTime.SpecifyKind(i, DateTimeKind.Utc));
cfg.CreateMap<DateTime?, DateTime?>().ConvertUsing(i => DateTime.SpecifyKind(i.Value, DateTimeKind.Utc));

或者

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

或者

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

我也试过这个但是在对文档进行一些挖掘之后,使用ProjectTo

时,ResolveUsing似乎不起作用
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;
        });
});

我这样做是错误的还是有更好的方法来尝试实现这个目标?

0 个答案:

没有答案