我有一个有效日期的字符串,但它是一个字符串,它需要是一个字符串.但是,当我尝试将其自动映射到日期时,它会抛出异常
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.
Run Code Online (Sandbox Code Playgroud)
我希望它会进行自动转换,但我想我必须告诉它如何做到这一点.
我怎么能告诉它转换?
Roo*_*ian 16
创建映射并使用转换器:
CreateMap<string, DateTime>().ConvertUsing<StringToDateTimeConverter>();
Run Code Online (Sandbox Code Playgroud)
转换器:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试了以下但这不起作用,我不知道为什么:
CreateMap<string, DateTime>().ForMember(d => d, opt => opt.MapFrom(x => DateTime.Parse(x)));
Run Code Online (Sandbox Code Playgroud)
如果有人知道为什么这不起作用,请告诉我:)
| 归档时间: |
|
| 查看次数: |
9648 次 |
| 最近记录: |