如何在自动映射器中将字符串映射到日期?

编程入门 行业动态 更新时间:2024-10-25 06:21:11
本文介绍了如何在自动映射器中将字符串映射到日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

如何在自动映射器中将字符串映射到日期?

本文发布于:2023-11-26 17:28:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634510.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   中将   日期   如何在   映射器

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!