繁体   English   中英

如何在自动映射器中将字符串 map 转换为日期?

[英]How to map a string to a date in automapper?

我有一个有效日期的字符串,但它是一个字符串,它必须是一个字符串。 但是,当我尝试将 map 自动设置为日期时间时,它会引发异常

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.

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

我怎样才能告诉它转换?

创建映射并使用转换器:

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

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

这是一个旧帖子,但总是需要。 我正在使用 AutoMapper(11.0.1) 和 Core (6)

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

这对我来说可以。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM