自动将一个源映射到多个目标 [英] Automapper one source to multiple destination
问题描述
下面是我的课程
class Dest1
{
string prop1;
string prop2;
strig prop3;
public Dest2 Dest2 {get;set;}
pubic List<Dest3> Dest3 {get;set;}
}
class Dest2
{
string prop4;
string prop5;
strig prop6;
}
class Dest3
{
string prop7;
}
class Source1
{
string prop1;
string prop2;
string prop3;
string prop4;
}
class Source2
{
string prop7;
}
我需要地图
Q1.从source1类到Dest1类(我也需要映射dest2对象)
Q1. source1 class to Dest1 Class( also i need to map dest2 object)
Q2.我需要将Dest1映射回源1(反向映射)
Q2. I need to do map Dest1 back to Source 1 (reverse map)
Am使用.net核心和自动映射器.对于automapper& .net核心..提前感谢
Am using .net core and auto mapper.. am new to automapper & .net core ..Thanks in advance
推荐答案
如果您配置了映射,则AutoMapper可以从多个源映射到任意多个目的地.例如,您请求的方案:
AutoMapper can map from as many sources to as many destinations as you would like, assuming you configure the mapping. For example, your requested scenario:
var configuration = new MapperConfiguration(cfg =>
// Mapping Config
cfg.CreateMap<Source1, Dest2>()
.ForMember(dest => dest.prop5, opt => opt.Ignore())
.ForMember(dest => dest.prop6, opt => opt.Ignore());
cfg.CreateMap<Source1, Dest1>()
.ForMember(dest => dest.Dest2, opt => opt.MapFrom(src => src));
// Reverse Mapping Config
cfg.CreateMap<Dest1, Source1>()
.ForMember(dest => dest.prop4,
opt => opt.MapFrom(src => (src?.Dest2 != null) // ?. w/c#6
? src.Dest2.prop4 // map if can
: null)); // otherwise null
);
// Check AutoMapper configuration
configuration.AssertConfigurationIsValid();
具有相同名称的属性将自动映射.任何没有相应来源属性的目标属性都将被忽略.
Properties with the same name will map automatically. Any destination properties that don’t have a corresponding source property will need to be ignored.
一旦配置了AutoMapper,就可以使用IMapper界面根据需要进行映射.
Once your AutoMapper is configured, you can map as needed with the use of the IMapper interface.
public class Foo {
private IMapper _mapper;
public Foo(IMapper mapper) {
_mapper = mapper;
}
// Map Source1 -> Dest1
public Dest1 Bar(Source1 source) {
return _mapper.Map<Dest1>(source);
}
// Map Dest1 -> Source1
public Source1 Baz(Dest1 dest) {
return _mapper.Map<Source1>(dest);
}
}
这篇关于自动将一个源映射到多个目标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!