c# - 如何将字符串映射到自动映射器中的日期?

标签 c# automapper

我有一个字符串,它是一个有效的日期,但它是一个字符串,而且它必须是一个字符串。但是,当我尝试将其自动映射到日期时间时,它会抛出异常

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

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

关于c# - 如何将字符串映射到自动映射器中的日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4911108/

相关文章:

.net - FxCop 10.0 独立无法分析使用 AutoMapper 的程序集

java - C#和Java的三元运算符的区别(?:)

c# - string1 中有多少个 string2?

c# - 该进程无法访问文件\App_Data\ASPNETDB.MDF',因为它正在被另一个进程使用。

automapper - 使用 AutoMapper 全局应用值解析器

c# - 如何在解决方案中将 Automapper 4.2.1 升级到 6.1.1。我缺少什么?

c# - LINQ 和 AutoMapper

list - 使用 AutoMapper 对特定属性进行自定义转换

c# - 从 ASP.NET WebAPI 应用程序调用 Web 服务

c# - 字符串替换的正则表达式模式