首先我使用的是automapper 4.2.1。我有一个代表树视图节点的类。例如,这个类有三个属性和一个方法:
class A
{
public string Name{get; set;}
public bool IsExpanded{get; set;}
public ObservableCollection<A> Children {get; set;}
public void UpdateCurrenNode(A object)
{
Mapper.Map(object, this);
}
}
正如您所看到的,我有一个方法可以帮助我使用给定对象更新当前节点及其后代。但我想忽略属性IsExanded。所以这是我的地图:
CreateMap<A, A>().ForMember(dest => dest.IsExpanded, opts => opts.Ignore());
但是映射属性IsExpanded仅在根对象时被忽略,但对于后代不会被忽略。我哪里错了?
谢谢!此致,德米特里
答案 0 :(得分:1)
请尝试:
CreateMap<A, A>().ForMember(dest => dest.IsExpanded, opts => opts.Ignore())
.ForMember(dest => dest.Children,
opt => opt.MapFrom(src =>
src.Children.Select(Mapper.Map<A, A>).ToList()));
例如:
A类
public class A
{
private static MapperConfiguration config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<A, A>().ForMember(dest => dest.IsExpanded, opts => opts.Ignore())
.ForMember(dest => dest.Children,
opt => opt.MapFrom(src => src.Children.Select(Mapper.Map<A, A>).ToList()));
});
private static IMapper mapper = config.CreateMapper();
public string Name{get; set;}
public bool IsExpanded{get; set;}
public ObservableCollection<A> Children {get; set;}
public void UpdateCurrenNode(A obj)
{
mapper.Map(obj, this);
}
}
程序
var test1 = new A()
{
IsExpanded = true,
Name = "Test1",
Children = new ObservableCollection<A>()
};
var test2 = new A()
{
IsExpanded = true,
Name = "Test2",
Children = new ObservableCollection<A>()
};
var test3 = new A()
{
IsExpanded = true,
Name = "Test3",
Children = new ObservableCollection<A>()
};
var test = new A()
{
IsExpanded = true,
Name = "Test",
Children = new ObservableCollection<A>() {test1, test2, test3}
};
var clone = new A()
{
Children = new ObservableCollection<A>()
};
clone.UpdateCurrenNode(test);
上面的示例也适用于原始配置:
cfg.CreateMap<A, A>().ForMember(dest => dest.IsExpanded, opts => opts.Ignore());