我有一个像这样的一对多关系的POCO / DTO:
Public Class Main1
Public A As Integer
Public Subs As New List(Of Sub1)
End Class
Public Class Sub1
Public B As Integer
End Class
我有一个业务逻辑部分,如下所示:
Public Class Main2
Public A As Integer
Public Subs As New Sub2Set()
End Class
Public Class Sub2Set
Public Subs As New List(Of Sub2)
Public Sub Add(ByVal Sub2 As Sub2)
'Do some validation checks here.
Me.Subs.Add(Sub2)
End Sub
End Class
Public Class Sub2
Public B As Integer
End Class
我正在使用Sub2Set
到(1)只公开相关的方法,并且(2)检查以确保添加的Sub2
不违反我们的任何规则。
如何使用automapper将Main1及其子节点映射到Main2,反之亦然?
答案 0 :(得分:0)
到目前为止我已经朝着一个方向努力了:
AutoMapper.Mapper.CreateMap(Of Sub1, Sub2)()
AutoMapper.Mapper.CreateMap(Of List(Of Sub1), Sub2Set)().ForMember(Function(d) d.Subs, Sub(o) o.MapFrom(Function(s) s))
AutoMapper.Mapper.CreateMap(Of Main1, Main2)().ForMember(Function(d) d.Subs, Sub(o) o.ResolveUsing(Of SubResolver)())
Dim Main2 As Main2 = AutoMapper.Mapper.Map(Of Main2)(Main1)
使用自定义解析器
Public Class SubResolver
Inherits AutoMapper.ValueResolver(Of Main1, Sub2Set)
Protected Overrides Function ResolveCore(ByVal source As Main1) As Sub2Set
Return AutoMapper.Mapper.Map(Of Sub2Set)(source.Subs)
End Function
End Class