![](/img/trans.png)
[英]AutoMapper behaviour with readonly properties in source not being mapped to destination
[英]Using AutoMapper how can a source value be validated before being mapped?
我有一个从 DateTime 定义为字符串的 AutoMapper 映射,其中我使用 ISO-8601 日期格式并截断时间部分。
我想对源值严格执行 DateTime.Kind == DateTimeKind.Utc,这样如果源日期不是 DateTimeKind.Utc 我希望映射失败,即抛出异常。
这是解决这个问题的正确方法吗? 如果是这样,实现这一目标的正确方法是什么?
这是我的映射配置文件:
public DateTimeMappingProfile()
{
// TODO: Ideally we would throw an exception if DateTime.Kind is not UTC.
CreateMap<DateTime, string>()
.ConvertUsing(dt => dt.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
CreateMap<string, DateTime>()
.ConvertUsing(s => DateTime.ParseExact(s, "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal));
}
您可以使用接受映射函数(而不是表达式)的ConvertUsing
重载。
void ConvertUsing(Func<TSource, TDestination, TDestination> mappingFunction)
这一个允许有一个Exception
抛出。
CreateMap<DateTime, string>()
.ConvertUsing((source, destination) => source.Kind == DateTimeKind.Utc
? source.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)
: throw new Exception("DateTime must be of kind Utc")
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.