我将 AutoMapper V3.3.1 更新到 V6.1.1,令我惊讶的是,在将所有 CreateMaps() 放入配置文件之后,它实际上一开始就完美运行——对我来说几乎是可怕的。
我遇到的问题是它正在使用 AutoMapper 文档中建议的以下代码:
Private Sub InitiatizeAutoMapper()
Mapper.Initialize(Function(cfg)
cfg.AddProfile(Of MappingProfile)()
End Function)
End Sub
但是代码发出警告:
Warning BC42105 Function '<anonymous method>' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used.
如果我向 Lambda 添加返回值,例如:
Private Sub InitiatizeAutoMapper()
Mapper.Initialize(Function(cfg)
Return cfg.AddProfile(Of MappingProfile)()
End Function)
End Sub
然后我收到以下错误:
Error BC30518 Overload resolution failed because no accessible 'Initialize' can be called with these arguments:
'Public Shared Overloads Sub Initialize(config As Action(Of IMapperConfigurationExpression))': Expression does not produce a value.
'Public Shared Overloads Sub Initialize(config As Action(Of IMapperConfigurationExpression))': Expression does not produce a value.
'Public Shared Overloads Sub Initialize(config As MapperConfigurationExpression)': Lambda expression cannot be converted to 'MapperConfigurationExpression' because 'MapperConfigurationExpression' is not a delegate type.
现在 - 如果我把它变成一个 Sub 而不是一个函数,它一切正常,没有这样的错误:
Private Sub InitiatizeAutoMapper()
Mapper.Initialize(Sub(cfg)
cfg.AddProfile(Of MappingProfile)()
End Sub)
End Sub
我知道这可能会令人头疼,但我正在尝试遵循文档,并且害怕将其发布到生产中,因为我可能会遗漏一些东西。
编辑:
我选择分解多行 lambda 以使其对我来说更容易一些,这也很方便地利用 IntelliSense 选项以供将来增强。虽然它可能不是“最酷”的代码,但我发现它非常易读。
Private Sub InitiatizeAutoMapper()
Dim config As New Configuration.MapperConfigurationExpression : With config
.AddProfile(Of MappingProfile)()
End With
Mapper.Initialize(config)
End Sub