C#自动映射器将日期时间格式化为ISO字符串

当Automapper将转换为对象的DateTime转换为字符串时,它将使用ToString()方法以文化定义的格式返回字符串.如何配置它,使其始终映射到ISO字符串?

        var data = new Dictionary<string, object>
        {
            { "test", new DateTime(2016, 7, 6, 9, 33, 0) }
        };

        var config = new MapperConfiguration(cfg =>
        {
            cfg.CreateMap<DateTime, string>().ConvertUsing(dt => dt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"));
        });

        var mapper = config.CreateMapper();

        Assert.AreEqual("2016-07-06T07:33:00Z", mapper.Map<string>(data["test"]));
        Assert.AreEqual("2016-07-06T07:33:00Z", mapper.Map<IDictionary<string, string>>(data)["test"]);

第一个断言很好,但是第二个断言失败:

Result Message: 
Expected string length 20 but was 17. Strings differ at index 0.
  Expected: "2016-07-06T07:33:00Z"
  But was:  "6-7-2016 09:33:00"
  -----------^

解决方法:

这是一个示例,您可以如何执行此操作:

示例模型:

class A
{
    public DateTime DateTime { get; set; }
}

class B
{
    public string DateTime { get; set; } 
}

程式码片段:

static void Main()
{
    var config = new MapperConfiguration(
        cfg =>
            {
                cfg.CreateMap<A, B>();
                cfg.CreateMap<DateTime, string>().ConvertUsing(dt => dt.ToString("u"));
            });

    var mapper = config.CreateMapper();

    var a = new A();

    Console.WriteLine(a.DateTime); // will print DateTime.ToString
    Console.WriteLine(mapper.Map<B>(a).DateTime); // will print DateTime in ISO string
    Console.ReadKey();
}

代码片段2:

static void Main()
{
    var data = new Dictionary<string, DateTime> // here is main problem
    {
        { "test", new DateTime(2016, 7, 6, 9, 33, 0) }
    };

    var config = new MapperConfiguration(cfg =>
    {
        cfg.CreateMap<DateTime, string>().ConvertUsing(dt => dt.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"));
    });

    var mapper = config.CreateMapper();

    Console.WriteLine(mapper.Map<string>(data["test"]));
    Console.WriteLine(mapper.Map<IDictionary<string, string>>(data)["test"]);
    Console.ReadKey();
}
上一篇:c#-将平面JSON /字典映射到模型(包含子类)


下一篇:c# – AutoMapper AfterMap