如何在自动映射器中将字符串映射到日期? [英] How to map a string to a date in automapper?

查看:203
本文介绍了如何在自动映射器中将字符串映射到日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

转换器:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆