簡體   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