gpt4 book ai didi

c# - AutoMapper 和展平嵌套数组

转载 作者:太空狗 更新时间:2023-10-29 18:20:26 24 4
gpt4 key购买 nike

我正在尝试使用 AutoMapper 展平多级数组。

考虑以下源类:

class X {
public string A { get; set; }
public Y[] B { get; set; }
}

class Y {
public string C { get; set; }
public Z[] D { get; set; }
}

class Z {
public string E { get; set; }
public string F { get; set; }
}

以及以下目的地:

class Destination {
public string A { get; set; }
public string C { get; set; }
public string E { get; set; }
public string F { get; set; }
}

我想做的是从一个或多个 X 中获取一个列表,例如:

Mapper.Map<IEnumerable<X>, IEnumerable<Destination>>(arrayOfX);

我无法弄清楚要使用哪种映射配置来实现此目的。 MapFrom 似乎是 1:1 组合的方式,但似乎无法处理数组(或其他可枚举的),除非我使用 AutoMapper 的目标命名约定。

关于如何实现这一目标的任何见解?

最佳答案

试试这个映射器,

Mapper.CreateMap<Z, Destination>();
Mapper.CreateMap<Y, Destination>();
Mapper.CreateMap<X, Destination>()
.ForMember(destination => destination.A, options => options.MapFrom(source => source.A)).IgnoreAllNonExisting()
.ForMember(destination => destination.C, options => options.MapFrom(source => Mapper.Map<IEnumerable<Y>, IEnumerable<Destination>>(source.B).FirstOrDefault().C))
.ForMember(destination => destination.E, options => options.MapFrom(source => Mapper.Map<IEnumerable<Z>, IEnumerable<Destination>>(source.B.SelectMany(d => d.D)).FirstOrDefault().E))
.ForMember(destination => destination.F, options => options.MapFrom(source => Mapper.Map<IEnumerable<Z>, IEnumerable<Destination>>(source.B.SelectMany(d => d.D)).FirstOrDefault().F));

var result = Mapper.Map<IEnumerable<X>, IEnumerable<Destination>>(arrayOfX);

关于c# - AutoMapper 和展平嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13338262/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com