Bja*_*ðar 6 c# automapper automapper-2
使用Automapper 2.0映射内部对象的最佳方法是什么?
使用此问题中的解决方案(Automapper 1.0)
创建自定义值解析器
?
public class DTOObject
{
// MainObject
public int Id { get; set; }
public string Name { get; set; }
// SubObject (TopObject)
public string TopText { get; set; }
public string TopFont { get; set; }
// SubObject (BottomObject)
public string BottomText { get; set; }
public string BottomFont { get; set; }
}
public class MainObject
{
public int Id { get; set; }
public string Name { get; set; }
public SubObject TopObject { get; set; }
public SubObject BottomObject { get; set; }
}
public class SubObject
{
public string SubPropText { get; set; }
public string SubPropFont { get; set; }
}
Run Code Online (Sandbox Code Playgroud)自定义值解析器
public class CustomResolver : ValueResolver<DTOObject, SubObject>
{
protected override SubObject ResolveCore(DTOObject source)
{
return Mapper.Map<DTOObject, SubObject>(source);
}
}
Run Code Online (Sandbox Code Playgroud)
小智 7
对我来说,可以只使用MapFrom(没有ResolveUsing,这使你有机会使用这个映射与IQueryable扩展).因此,您将在Automapper配置中获得以下内容:
Mapper.CreateMap<DTOObject, SubObject>()
.ForMember(dest => dest.SubPropText, opt => opt.MapFrom(x => x.BottomText))
.ForMember(dest => dest.SubPropFont, opt => opt.MapFrom(x => x.BottomFont));
Mapper.CreateMap<DTOObject, MainObject>()
.ForMember(dest => dest.SubPart, opt => opt.MapFrom(x => x));
Run Code Online (Sandbox Code Playgroud)