我有一个字符串,它是一个有效的日期,但它是一个字符串,而且它必须是一个字符串。但是,当我尝试将其自动映射到日期时间时,它会抛出异常
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)));
如果有人知道为什么这不起作用,请告诉我:)
关于c# - 如何将字符串映射到自动映射器中的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4911108/