Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AutoMapper inconsistently automatically resolving string -> DateTime

My expectation is that AutoMapper (3.3.0) does not automatically resolve string -> DateTime conversions, even when the string is in a well-understood format. The lack of inclusion of a default string -> DateTime converter is noted (albeit four years ago) in a comment by the library author, Jimmy Bogard, on this StackOverflow answer: https://stackoverflow.com/a/4915449/1675729

However, I have a .NET Fiddle which seems to suggest that AutoMapper can handle this mapping by default: https://dotnetfiddle.net/dDtUGx

In that example, the Zing property is mapped from a string in Foo to a DateTime in Bar without a custom mapping or resolver being specified.

However, when this code runs in my solution unit tests (using the same AutoMapper version), it produces the exception I expect, which is:

AutoMapper.AutoMapperMappingExceptionMissing type map configuration or unsupported mapping.
Mapping types:  
    String -> DateTime
    System.String -> System.DateTime
Destination path:
    Bar.Zing
Source value:
    Friday, December 26, 2014

What is causing this inconsistent behavior?

For completeness, the code inside the .NET Fiddle is reproduced here:

using System;
using AutoMapper;

public class Program
{
    public static void Main()
    {
        var foo = new Foo();
        foo.Zing = DateTime.Now.ToLongDateString();
        Mapper.CreateMap<Foo, Bar>();
        var bar = Mapper.Map(foo, new Bar());
        Console.WriteLine(bar.Zing);
    }


    public class Foo
    {       
        public string Zing { get; set; }    
    }

    public class Bar 
    {
        public DateTime Zing { get; set; }
    }
}
like image 607
NWard Avatar asked Nov 10 '22 21:11

NWard


1 Answers

I believe since Automapper v2.0 the string to DateTime conversion is handled by an internal IObjectMapper called TypeConverterMapper, but looking at the source, this appears to be platform specific: only some of the platforms (.Net full, SL5, WinRT) provide this mapper. The "portable" .Net assembly doesn't have this platform specific mapper.

If your unit tests are referencing the portable assembly of Automapper 3.3.0, you get the error. If they reference the full .Net 4.0 assembly, the mapping will succeed.

like image 92
codekaizen Avatar answered Nov 14 '22 23:11

codekaizen