使用记录自动映射到 AutoMapper 中的子对象
Automatically map to a subobject in AutoMapper with records
我有一个源对象和一个目标对象。
源对象嵌套在包装器对象中:
record Source(string Field1, string Field2);
record Destination(string Field1, string Field2);
record Wrapper(Source Item);
因此,在映射时我想打开对象,因为我不关心包装器。
是否可以创建一个不涉及逐个映射每个字段的映射(这些字段确实具有相同的名称)?
测试和阅读文档,目前我发现的是:
cfg.CreateMap<Wrapper, Destination>().IncludeMembers(s => s.Item);
cfg.CreateMap<Source, Destination>();
适用于 类,但不适用于记录:它抛出 Destination needs to have a constructor with 0 args or only optional args
我想我明白为什么(我猜想嵌套对象的属性以对象名称为前缀:ItemField1
、ItemField2
,所以当它试图将它们与构造函数参数名称匹配时,它找不到任意匹配)。
我不确定这是否应该被视为错误或预期行为(或不受支持的情况),但这非常令人沮丧。
那么,还有另一种方法可以进行映射吗?
您可以使用 Type Converter 函数提取 Source
实例并将该实例映射到 Destination
:
cfg.CreateMap<Source, Destination>();
cfg.CreateMap<Wrapper, Destination>()
.ConvertUsing((wrapper, destination, context) =>
context.Mapper.Map<Destination>(wrapper.Item));
我有一个源对象和一个目标对象。
源对象嵌套在包装器对象中:
record Source(string Field1, string Field2);
record Destination(string Field1, string Field2);
record Wrapper(Source Item);
因此,在映射时我想打开对象,因为我不关心包装器。
是否可以创建一个不涉及逐个映射每个字段的映射(这些字段确实具有相同的名称)?
测试和阅读文档,目前我发现的是:
cfg.CreateMap<Wrapper, Destination>().IncludeMembers(s => s.Item);
cfg.CreateMap<Source, Destination>();
适用于 类,但不适用于记录:它抛出 Destination needs to have a constructor with 0 args or only optional args
我想我明白为什么(我猜想嵌套对象的属性以对象名称为前缀:ItemField1
、ItemField2
,所以当它试图将它们与构造函数参数名称匹配时,它找不到任意匹配)。
我不确定这是否应该被视为错误或预期行为(或不受支持的情况),但这非常令人沮丧。
那么,还有另一种方法可以进行映射吗?
您可以使用 Type Converter 函数提取 Source
实例并将该实例映射到 Destination
:
cfg.CreateMap<Source, Destination>();
cfg.CreateMap<Wrapper, Destination>()
.ConvertUsing((wrapper, destination, context) =>
context.Mapper.Map<Destination>(wrapper.Item));