如何将字符串映射到automapper中的日期?

时间:2011-02-06 02:22:31

标签: c# automapper

我有一个有效日期的字符串,但它是一个字符串,它需要是一个字符串。但是,当我尝试将其自动映射到日期时,它会抛出异常

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.

我希望它可以进行自动转换,但我想我必须告诉它如何做到这一点。

如何判断它转换?

1 个答案:

答案 0 :(得分:13)

创建映射并使用转换器:

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)));

如果有人知道为什么这不起作用,请告诉我:)。