【问题标题】:C# automapper format datetime to iso stringC# automapper 将日期时间格式转换为 iso 字符串
【发布时间】:2016-07-06 21:02:32
【问题描述】:

当 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"
  -----------^

【问题讨论】:

  • 如果您想为 all 日期时间执行此操作,您只需创建一个TypeConverter。如果您想对特定值执行此操作,请在这些属性上使用 ForMember 语法。
  • @stuartd 我试过的是: Mapper.CreateMap().ConvertUsing(x => x.ToString("u"));但是,这似乎从未被称为
  • 这看起来可行。你能设置一个失败的测试用例吗?

标签: c# automapper


【解决方案1】:

下面是一个示例:

示例模型:

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

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

代码 sn-p:

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

【讨论】:

  • 您的示例确实运行良好,而且我发现问题更加复杂。请查看更新后的帖子。
  • 我添加了 sn-p #2。您的代码中的问题是您的字典中的 &lt;string, object&gt;, not the . I believe that in case with collection mappings it uses the declared type of collection, but not the actual one. As you can see, if you'll change from object` 到 DateTime - 它会起作用。
  • 问题是,它是Dictionary&lt;string,object&gt; 是有原因的——它可以包含日期时间,也可以包含字符串、数字或其他任何内容。如果没有其他方法可以做到这一点,我想我们将进行一些重新设计......
  • @BartvandenBurg 再造应该是要走的路。当有泛型类型时,它不应该使用对象。
猜你喜欢
  • 2015-04-27
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-10
  • 2015-11-16
相关资源
最近更新 更多