How to map a string to a date in automapper?

2019-04-26 12:30发布

问题:

I have a string that is a valid date but it is a string and it needs to be a string. However when I try to auto map it to a datetime it throws an exception

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.

I would have hoped that it would do an auto convert but I guess I have to tell it some how to do this.

How can I tell it to convert?

回答1:

Create a mapping and use a converter:

CreateMap<string, DateTime>().ConvertUsing<StringToDateTimeConverter>();

Converter:

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

I tried the following but this does not work and I do not know why:

CreateMap<string, DateTime>().ForMember(d => d, opt => opt.MapFrom(x => DateTime.Parse(x)));

If someone know why this does not work, let me know :)



标签: c# AutoMapper