如果头对象的prop设置为1,那么它应该映射子域中的字段type1以在目标中键入。否则它应该使用type2。
如果填充扩展器,我可以使用IValueResolver
使用类型1或类型1扩展。
这是我最小的可行产品/演示
using AutoMapper;
using AutoMapper.Configuration.Conventions;
using System;
using System.Collections.Generic;
namespace ConsoleAppAutoMapper
{
class Program
{
static void Main(string[] args)
{
var source = new SourceParent() {
Header = new SourceHeader() { Currency = 30, FileName = "testfile.txt", Type = 1 },
Rows = new List<SourceRow>() {
new SourceRow() { ID = 1, Amount1 = 100, Amount2 = 200 },
new SourceRow() { ID = 2, Amount1 = 101, Amount2 = 201 },
new SourceRow() { ID = 3, Amount1 = 102, Amount2 = 202 }
} };
var config = new MapperConfiguration(cfg => {
cfg.CreateMap<SourceParent, DestinationParent>();
cfg.CreateMap<SourceRow, DestinationRow>()
.ForMember(x => x.Type, opt => opt.MapFrom(p => p.Type1));
});
var mapper = config.CreateMapper();
var dest = mapper.Map<DestinationParent>(source);
Console.WriteLine(dest.Rows[0].Type == 100); // should be true if SourceHeader.Type = 1 and should be 200 (SourceRow.Type2) if SourceHeader.Type = 2
Console.ReadKey();
}
}
// source
public class SourceParent
{
public SourceHeader Header { get; set; }
public List<SourceRow> Rows { get; set; }
}
public class SourceHeader
{
public string FileName { get; set; }
public int Type { get; set; }
}
public class SourceRow
{
public int ID { get; set; }
public int Amount1 { get; set; }
public int Amount2 { get; set; }
}
//destination
public class DestinationParent
{
public DestinationHeader Header { get; set; }
public List<DestinationRow> Rows { get; set; }
}
public class DestinationHeader
{
public string FileName { get; set; }
}
public class DestinationRow
{
public int ID { get; set; }
public int Type { get; set; }
public int Amount{ get; set; } // if type=1 then source is amount1 otherwise amount2
}
}
编辑我试图通过在sourceparent映射上有一个Aftermap
来解决它,它从标题中获取值并将它放在目标内的一个道具中(它是Type
值)并想要在行上的另一个后贴图来查看我是否需要道具A或B(type1或type2)但是aftermap仍然不知道(它为null)它是什么类型,因为它发生在它看起来像父的aftermap之前。
public class MapRowType : IMappingAction<SourceParent, DestinationParent>
{
public void Process(SourceParentsource, DestinationParent destination)
{
foreach (var row in destination.Rows)
{
row.Type = source.Header.Type; // so now I have type in the row, but still do not know if I should use Amount1 or Amount2
}
}
}
你可以使用分辨率上下文。声明映射:
cfg.CreateMap<SourceRow, DestinationRow>()
.ForMember(x => x.Type,
opt => opt.ResolveUsing((src, dest1, destMember, resContext) => resContext.Items["Type"] as int? == 1? src.Type2: src.Type1));
传递值后:
var dest = mapper.Map<DestinationParent>(source, opts=> { opts.Items["Type"] = source.Header.Type;});