Как сопоставить строку с датой в autopper? - PullRequest
7 голосов
/ 06 февраля 2011

У меня есть строка, которая является допустимой датой, но это строка, и она должна быть строкой. Однако, когда я пытаюсь автоматически сопоставить его с датой и временем, возникает исключение

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.

Я бы надеялся, что он выполнит автоматическое преобразование, но, думаю, мне придется кое-что рассказать, как это сделать.

Как я могу сказать, чтобы преобразовать?

1 Ответ

15 голосов
/ 06 февраля 2011

Создайте отображение и используйте конвертер:

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

Если кто-то знает, почему это не работает, дайте мне знать:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...