[英]Automapper / Mapster C# - how do I map collection from specific property?
It is weird but I am stuck with a pretty simple case:这很奇怪,但我遇到了一个非常简单的案例:
Say I have a class:假设我有一堂课:
class Record
{
public List<Data> Data {get; set;}
public string OtherProp1 {get; set;}
public string OtherProp2 {get; set;}
}
And I want to map a List<Model>
from it.我想从中映射一个
List<Model>
。 Which is basically:基本上是:
mapper.Map<List<Model>>(Record.Data);
But I want Mapster (or Mapper) to be able to make it right from the Record like this:但我希望 Mapster(或 Mapper)能够像这样从记录中正确地制作它:
mapper.Map<List<Model>>(Record);
So所以
mapper.Map<List<Model>>(Record.Data); // Works easily
mapper.Map<List<Model>>(Record); // Can't config properly
I did find one way with Mapster but it seems like cheating:我确实找到了一种使用 Mapster 的方法,但它似乎是在作弊:
var config = new TypeAdapterConfig();
config.ForType<Data, Model>();
config.ForType<Record, List<Model>>().MapWith(record => record.Data.Adapt<List<Model>>(config));
Because I sort of use Mapster inside of Mapster config )因为我有点在 Mapster 配置中使用 Mapster)
It must be the way to point the source path like this:它必须是这样指向源路径的方式:
config.ForType<Record, List<Model>>().Map(dest => dest, record => record.Data);
But all such attempts lead to:但所有这些尝试都会导致:
Expression 'dest => dest' must resolve to top-level member and not any child object's properties.表达式 'dest => dest' 必须解析为顶级成员,而不是任何子对象的属性。 You can use ForPath, a custom resolver on the child type, or the AfterMap option instead.
您可以使用 ForPath、子类型上的自定义解析器或 AfterMap 选项。 (Parameter 'lambdaExpression') -- using .ForMember().
(参数 'lambdaExpression') - 使用 .ForMember()。
Only member accesses are allowed.仅允许成员访问。 dest => dest (Parameter 'destinationMember') -- using .ForPath().
dest => dest(参数 'destinationMember') ——使用 .ForPath()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.