我有一个有效日期的字符串,但它是一个字符串并且它需要是一个字符串。但是,当我尝试将其自动映射到日期时间时,它会引发异常
Trying to map System.String to System.DateTime.
Trying to map System.String to System.DateTime.
Using mapping configuration for ViewModels.FormViewModel to Framework.Domain.Test
Destination property: DueDate
Missing type map configuration or unsupported mapping.
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: AutoMapper.AutoMapperMappingException: Trying to map System.String to System.DateTime.
Using mapping configuration for ViewModels.FormViewModel to
Framework.Domain.Task
Destination property: DueDate
Missing type map configuration or unsupported mapping.
Exception of type 'AutoMapper.AutoMapperMappingException' was thrown.
我本来希望它能进行自动转换,但我想我必须告诉它如何做到这一点。
我怎样才能告诉它转换?
创建映射并使用转换器:
CreateMap<string, DateTime>().ConvertUsing<StringToDateTimeConverter>();
转换器:
public class StringToDateTimeConverter: ITypeConverter<string, DateTime>
{
public DateTime Convert(ResolutionContext context)
{
object objDateTime = context.SourceValue;
DateTime dateTime;
if (objDateTime == null)
{
return default(DateTime);
}
if (DateTime.TryParse(objDateTime.ToString(), out dateTime))
{
return dateTime;
}
return default(DateTime);
}
}
我尝试了以下方法,但这不起作用,我不知道为什么:
CreateMap<string, DateTime>().ForMember(d => d, opt => opt.MapFrom(x => DateTime.Parse(x)));
如果有人知道为什么这不起作用,请告诉我:)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)