谁能解释一下 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 函数,这就是它包含值的方式。
您可能会注意到AfterMap是Lambda表达式(操作),使用反射将输入作为源和目标对象,可以轻松地将值从一个对象复制到 another.in 在这种情况下,只需执行操作,因为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
您可以在以下位置看到自动映射器的源代码
https://github.com/AutoMapper/AutoMapper/blob/32959279d8b81087d1c84903f56755cc57d35740/src/AutoMapper/Mappers/TypeMapObjectMapperRegistry.cs(第 98 行)
对象中有值,因为它们是在调用 Mapping.Map 函数之后调用的,这是传递带有值的实际对象的地方,然后调用 AfterMap 函数,这就是它在其中具有值的方式。