.net - 为什么 AutoMapper 仅在列表中的第一个元素上使用我的配置?

标签 .net automapper

这是我的 AutoMapper 配置:

Mapper.CreateMap<Source, Destination>()
      .ConstructUsing(s => new Destination(s.CreatedDate.DateTime));

这两个类都有一个属性,CreatedDate,但它们的类型不同:

public class Source
{
   public DateTimeOffset CreatedDate { get; set; }
}

public class Destination
{
   public Destination(DateTime created) { CreatedDate = created; }
   public DateTime CreatedDate { get; set; }
}

当我在一个实例化到另一个实例化之间映射时,此配置工作正常,但当我在这些类型的可枚举之间映射时会出现问题,如下所示:

var dests = Mapper.Map<IEnumerable<Source>, Destination[]>(sources);

在这种情况下,AutoMapper 会为要映射的第一个 元素调用 Destination 构造函数,但显然会继续自动映射其余元素。自动映射会引发异常,因为同名的 CreatedDate 属性属于不同类型。

如果我更改其中一个属性的名称(例如,Destination.Created),则会按照您的预期在所有元素上调用构造函数。

我正在使用最新版本的 AutoMapper (v1.1.0.188)。这看起来肯定是一个错误,但也许我忽略了一些东西?

最佳答案

您可能想尝试不同的方法。我会尝试:

Mapper.CreateMap<Source, Destination>()
      .ForMember(d => d.CreatedDate,
                 opt => opt.MapFrom(s => s.CreatedDate.DateTime));

映射稍微详细一些,但应该为每个元素正确处理。不仅如此,您现在还可以删除 Destination 类上多余的构造函数。

关于.net - 为什么 AutoMapper 仅在列表中的第一个元素上使用我的配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5329768/

相关文章:

c# - AutoMapper ResolveUsing 未被调用

automapper - 何时使用值格式化程序以及何时使用值解析器

.net - System.AddIn 管道应该安装在哪里?

C# 应用程序在 Windows 7 中运行,但不能在 Windows XP 中运行

c# - 命名约定 : How to name a different version of the same class?

c# - 带有 DataReader 的 AutoMapper DynamicMap 针对接口(interface)

AutoMapper 多对多关系转化为集合

c# - AutoMapper - 添加自定义格式化程序

c# - VSTO 加载项部署 - 我可以创建单个文件吗?

.net - 这个 xpath 意味着 "//Form/*[. = ' on']"