gpt4 book ai didi

c# - 自动映射器 - 使用集合映射对象

转载 作者:行者123 更新时间:2023-11-30 19:58:50 25 4
gpt4 key购买 nike

使用自动映射器,我需要映射以下类的对象

public class RemoteClass
{
public IEnumerable<RemoteDetails> collection{get; set;};

public int RemoteFieldA{get; set;}

public int RemoteFieldB{get; set;}
}


public class LocalClass
{
public IEnumerable<LocalDetails> collection{get; set;};

public int LocalFieldA{get; set;}

public int LocalFieldB{get; set;}
}

我的配置和映射应该是什么?

最佳答案

只需定义RemoteDetailsLocalDetails 之间的映射。 AutoMapper 足够聪明,可以处理他知道如何映射的类型集合。假设这两个类有字段 C:

Mapper.CreateMap<RemoteDetails, LocalDetails>()
.ForMember(ld => ld.LocalFieldC, opt => opt.MapFrom(rd => rd.RemoteFieldC));

Mapper.CreateMap<RemoteClass, LocalClass>()
.ForMember(lc => lc.LocalFieldA, opt => opt.MapFrom(rc => rc.RemoteFieldA))
.ForMember(lc => lc.LocalFieldB, opt => opt.MapFrom(rc => rc.RemoteFieldB));

通过这些映射,您可以从 RemoteClass 映射到 LocalClass:

RemoteClass remote = new RemoteClass {
RemoteFieldA = 42,
RemoteFieldB = 100,
collection = new [] {
new RemoteDetails { RemoteFieldC = "Foo" },
new RemoteDetails { RemoteFieldC = "Bar" }
}
};

var local = Mapper.Map<LocalClass>(remote);

结果:

enter image description here

关于c# - 自动映射器 - 使用集合映射对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25781492/

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