任何人都可以解释一下AfterMap函数如何初始化lambda表达式中传递的类对象?当我像我一样运行这段代码时,它会用我的详细信息填充dest对象。我无法弄清楚它是如何做到的?但如果有人能告诉我如何开始上课,那将有助于我朝着正确的方向前进。
AutoMapper.Mapper.CreateMap(Of Service.User, Models.User)() _
.ForMember(Function(dest As Models.User) dest.EmployeeNumber, Sub(opt) opt.MapFrom(Function(src As Service.User) src.IdentityNumber)) _
.AfterMap((Sub(src As Service.User, dest As Models.User)
'Extract the group names for the current application.
dest.Groups = New List(Of String)
Using service = ApplicationSecurityManager.Service.Factory.GetService()
Dim applicationPermissions = service.LoadPermissionsForUser(dest.Username, MyBase.EnvironmentCode)
If (Not applicationPermissions Is Nothing AndAlso applicationPermissions.Any(Function(x) x.Code = MyBase.ApplicationCode)) Then
dest.Groups = applicationPermissions.Single(Function(x) x.Code = MyBase.ApplicationCode).GroupNames.ToList()
End If
End Using
End Sub))
-------用答案编辑----
对象中包含值,因为它们是在调用Mapping.Map函数之后调用的,而且是传递带有值的实际对象,然后调用AfterMap函数,以及它是如何包含值的。
答案 0 :(得分:1)
你可能会注意到AfterMap是Lambda Expression(Action),使用Reflection作为源和目标对象,可以轻松地将值从一个Object复制到另一个Object。在这种情况下,只需要执行Action,因为Func只是一个委托而你刚刚定义了该方法(在Lambda中)。事实上,上述语句可能被重写为
AutoMapper.Mapper.CreateMap(Of Service.User, Models.User)() _
.ForMember(Function(dest As Models.User) dest.EmployeeNumber, Sub(opt) opt.MapFrom(Function(src As Service.User) src.IdentityNumber)) _
.AfterMap(AfterProc)
.....
Public Sub AfterProc(ByVal src As Service.User,ByVal dest As Models.User)
'Extract the group names for the current application.
dest.Groups = New List(Of String)
Using service = ApplicationSecurityManager.Service.Factory.GetService()
Dim applicationPermissions = service.LoadPermissionsForUser(dest.Username, MyBase.EnvironmentCode)
If (Not applicationPermissions Is Nothing AndAlso applicationPermissions.Any(Function(x) x.Code = MyBase.ApplicationCode)) Then
dest.Groups = applicationPermissions.Single(Function(x) x.Code = MyBase.ApplicationCode).GroupNames.ToList()
End If
End Using
End Sub
End Sub
您可以在
看到AutoMapper的来源答案 1 :(得分:0)
对象中包含值,因为它们是在调用Mapping.Map函数之后调用的,并且传递带有值的实际对象,然后调用AfterMap函数,以及它是如何具有值的在它。