Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map a string to a date in automapper?

Tags:

c#

automapper

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?

like image 235
chobo2 Avatar asked Feb 06 '11 02:02

chobo2


1 Answers

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

like image 151
Rookian Avatar answered Sep 27 '22 19:09

Rookian