2012-07-18 80 views
1

所以我有这个;AutoMapper - 嵌套映射,同时保留选定的子属性

public class Parent 
{ 
    public string SomeProperty { get; set; } 
    public Child ChildProperty { get; set; } 
} 
public class Child 
{ 
    public string ChildProperty { get; set; } 
    public string OtherChildProperty { get; set; } 
} 
public class Flat 
{ 
    public string SomeProperty { get; set; } 
    public string ChildProperty { get; set; } 
} 

然后我这样做;

Flat source = new Flat { SomeProperty = "test", ChildProperty = "test" }; 
Parent dest = GetParentFromDataContext(); 

Mapper.Map<Flat,Parent>(source,dest); 

然后我的期望是,dest.ChildProperty.OtherChildProperty仍设置为不管它是什么,当它被从DataContext的拉动。不过,我正在努力做到这一点。

如果我CreateMap这样,那么我得到一个“必须解析为顶级成员”的异常;

Mapper.CreateMap<Flat,Parent>() 
    .ForMember(dest => dest.Parent.ChildProperty.ChildProperty, 
    options => options.MapFrom(source => source.ChildProperty)) 
    .ForMember(dest => dest.Parent.ChildProperty.OtherChildProperty, 
    options => options.Ignore()); 

但是,如果我这样做,那么new Child {}替换从本质上DataContext的结算OtherChildPropertyChild;

Mapper.CreateMap<Flat,Parent>() 
    .ForMember(dest => dest.Child 
    options => options.MapFrom(source => new Child { ChildProperty = source.ChildProperty })); 

如何映射这个并保留我希望忽略的子属性?

回答

1

不雅,但这个工程;

Mapper.CreateMap<Flat,Parent>() 
    .ForMember(dest => dest.ChildProperty, options => options.Ignore()); 
Mapper.CreateMap<Flat,Child>() 
    .ForMember(dest => dest.OtherChildProperty, options => options.Ignore()); 

Mapper.Map<Flat,Parent>(source,dest); 
Mapper.Map<Flat,Child>(source,dest.Child); 
1

你正试图用automapper来扭转扁平化过程,这只是工作的错误工具。请参阅this SO问题。