复制数组而不是简单地在映射上分配引用
Copy array instead of simply assigning a reference on mapping
这是关于 Automapper 9 的。
假设您有两个 类,例如
public class Entity {
public byte[] RowVersion { get; set;
}
public class Model {
public byte[] RowVersion { get; set;
}
// mapping
CrateMap<Entity, Model>().ReverseMap();
映射时,AutoMapper 会简单地将数组的引用复制到目标。这对我有用,但只有当投影是从实体到模型的方向时。将模型映射回实体时,我想改为按值复制数组。
使用 type converter won't work since it has collateral effects as it is a global converter. A value converter 也不起作用,因为您无法访问目标 属性,而只能访问 return 字节数组的(新)实例。
理想情况下,我会在 CreateMap 上使用类型转换器(没有 ReverseMap),但我怀疑这是可能的。
所以我有点不知道如何正确地做到这一点。
如果我理解您的期望,我认为您可以使用 AfterMap
来访问源对象和目标对象
this.CreateMap<Entity, Model>()
.ReverseMap()
.ForMember(destEntity => destEntity.RowVersion, opt => opt.Ignore())
.AfterMap((srcModel, destEntity) =>
{
for (int i = 0; i < srcModel.RowVersion.Length; i++)
{
destEntity.RowVersion[i] = srcModel.RowVersion[i];
}
});
这是关于 Automapper 9 的。 假设您有两个 类,例如
public class Entity {
public byte[] RowVersion { get; set;
}
public class Model {
public byte[] RowVersion { get; set;
}
// mapping
CrateMap<Entity, Model>().ReverseMap();
映射时,AutoMapper 会简单地将数组的引用复制到目标。这对我有用,但只有当投影是从实体到模型的方向时。将模型映射回实体时,我想改为按值复制数组。 使用 type converter won't work since it has collateral effects as it is a global converter. A value converter 也不起作用,因为您无法访问目标 属性,而只能访问 return 字节数组的(新)实例。 理想情况下,我会在 CreateMap 上使用类型转换器(没有 ReverseMap),但我怀疑这是可能的。
所以我有点不知道如何正确地做到这一点。
如果我理解您的期望,我认为您可以使用 AfterMap
来访问源对象和目标对象
this.CreateMap<Entity, Model>()
.ReverseMap()
.ForMember(destEntity => destEntity.RowVersion, opt => opt.Ignore())
.AfterMap((srcModel, destEntity) =>
{
for (int i = 0; i < srcModel.RowVersion.Length; i++)
{
destEntity.RowVersion[i] = srcModel.RowVersion[i];
}
});