简体   繁体   English

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

[英]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但是,当我尝试将 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.

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)我正在使用 AutoMapper(11.0.1) 和 Core (6)

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

It works fine for me.这对我来说可以。

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

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