gpt4 book ai didi

c# - AutoMapper 中相同实体类型的不同映射规则

转载 作者:可可西里 更新时间:2023-11-01 09:13:44 24 4
gpt4 key购买 nike

我有两个实体:Order 和 OrderDTO 我正在使用 AutoMapper 将它们映射在一起。

基于某些条件,我希望这些实体以不同方式映射

事实上,我需要为这些实体使用两个或多个不同的映射规则 (CreateMap)。

并且在调用 Map 函数时,我想告诉引擎要使用哪个映射规则

感谢这个问题:Using the instance version of CreateMap and Map with a WCF service?一种方法是使用不同的映射器实例,这样每个实例都可以拥有自己的映射规则:

var configuration = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers());
var mapper = new MappingEngine(configuration);
configuration.CreateMap<Dto.Ticket, Entities.Ticket>()

你有更好的解决方案吗?

Jimmy Bogard(AutoMapper 的创建者) 所述:Using Profiles in Automapper to map the same types with different logic :

You're better off creating separate Configuration objects, and creating a separate MappingEngine for each. The Mapper class is merely a static facade over each of those, with some lifecycle management.

需要做哪些生命周期管理?

最佳答案

我最终创建了一个映射器的新实例并将它们缓存在共享(静态)并发字典中。

这是我的代码(vb.net):

映射器工厂:

Public Function CreateMapper() As IMapper Implements IMapperFactory.CreateMapper
Dim nestedConfig = New ConfigurationStore(New TypeMapFactory, MapperRegistry.Mappers)
Dim nestedMapper = New MappingEngine(nestedConfig)
Return New AutomapperMapper(nestedConfig, nestedMapper)
End Function

不同场景的不同配置文件:

Private Shared _mapperInstances As New Concurrent.ConcurrentDictionary(Of String, IMapper)

Public Shared ReadOnly Property Profile(profileName As String) As IMapper
Get
Return _mapperInstances.GetOrAdd(profileName, Function() _mapperFactory.CreateMapper)
End Get
End Property

和映射器类:

Friend Class AutomapperMapper
Implements IMapper

Private _configuration As ConfigurationStore
Private _mapper As MappingEngine

Public Sub New()
_configuration = AutoMapper.Mapper.Configuration
_mapper = AutoMapper.Mapper.Engine
End Sub

Public Sub New(configuration As ConfigurationStore, mapper As MappingEngine)
_configuration = configuration
_mapper = mapper
End Sub

Public Sub CreateMap(Of TSource, TDestination)() Implements IMapper.CreateMap
_configuration.CreateMap(Of TSource, TDestination)()
End Sub

Public Function Map(Of TSource, TDestination)(source As TSource, destination As TDestination) As TDestination Implements IMapper.Map
Return _mapper.Map(Of TSource, TDestination)(source, destination)
End Function

Public Function Map(Of TSource, TDestination)(source As TSource) As TDestination Implements IMapper.Map
Return _mapper.Map(Of TSource, TDestination)(source)
End Function


End Class

关于c# - AutoMapper 中相同实体类型的不同映射规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16995451/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com