0

我有一个 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,反之亦然?

4

1 回答 1

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
于 2013-11-06T21:25:24.397 回答