我正在寻找一种方法让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
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;
});
});
我这样做是错误的还是有更好的方法来尝试实现这个目标?