开发者

How to map a string to a date in 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?


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


It is a old post but always needed. I am using AutoMapper(11.0.1) and Core (6)

CreateMap<Source, Destination>() .ForMember(x => x.SourceDateString, y => y.MapFrom(z => DateTime.ParseExact(z.DestinationDateTime, "yyyyMMdd", CultureInfo.InvariantCulture)))

It works fine for me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜