【问题标题】:Automapper flatten entity to dtoAutomapper 将实体展平为 dto
【发布时间】:2014-01-17 16:50:11
【问题描述】:

目前我在使用自动映射器时遇到了一些问题。

我有一个具有以下属性的潜在客户实体

Id as long

FirstName as string

LastName as string

Title as string

LeadOpportunities as ICollection(Of ILeadOpportunity)

LeadOpportunity 包含以下属性

SourceDate as datetime

LeadOpportunityType as LeadOpportunityType

LeadOpportunityType 包含以下属性

Description as string

我有一个 LeadSearchDTO,它具有以下属性

LeadId as long

LastActionDate as datetime

Title as string

FirstName as string

LastName as string

Type as string

我的引导程序类中有以下内容。

Mapper.CreateMap(Of List(Of ILead), List(Of ILeadSearchDTO))()

Mapper.CreateMap(Of ILead, ILeadSearchDTO)().ForMember(Function(en) en.LeadId, Sub(map) map.MapFrom(Function(dto) dto.Id)) _
                                                    .ForMember(Function(en) en.LastActionDate, Sub(map) map.MapFrom(Function(dto) dto.LeadOpportunities.FirstOrDefault().SourceDate)) _
                                                    .ForMember(Function(en) en.Type, Sub(map) map.MapFrom(Function(dto) dto.LeadOpportunities.FirstOrDefault().LeadOpportunityType.Description))

然后我使用下面的代码来映​​射这两个对象。

response.LeadDTOs = Me._mapper.Map(Of List(Of ILead), List(Of ILeadSearchDTO))(leads)

当我将断点放在 response.LeadDTOs 上时,它不会从潜在客户集合中映射。

有人知道我可能会错过什么吗?我才刚刚开始使用 automapper 一个多星期,到目前为止我一直在使用简单的转换。

编辑:

如果我省略 Mapper.CreateMap(Of List(Of ILad), List(Of ILeadSearchDTO))() 它将给我以下错误消息。

Mapping types:
ILead -> ILeadSearchDTO
_8T.DataHub.Model.Interfaces.Entities.Lead.ILead ->  _8T.DataHub.Service.Interfaces.DTOs.Lead.ILeadSearchDTO

Destination path:
List`1[0]

Source value:
_8T.DataHub.Model.Implementation.Entities.Lead.Lead

我已经包含了 Mapper.AssertConfigurationIsValid()。

【问题讨论】:

  • 你必须映射到一个具体的类,AutoMapper 不能实现一个接口。

标签: asp.net-mvc automapper


【解决方案1】:

我觉得你不需要打电话

Mapper.CreateMap(Of List(Of ILead), List(Of ILeadSearchDTO))()

Automapper 会自动处理列表。但无论如何,尝试调用

Mapper.AssertConfigurationIsValid();

在最后一个CreateMap之后。

【讨论】:

    【解决方案2】:

    我终于解决了。

    我不得不使用下面的代码。

    ConstructUsing(Function(x As ResolutionContext) New LeadSearchDTO())
    

    【讨论】:

    • 不,你应该做Mapper.CreateMap(Of ILead, LeadSearchDTO)(没有接口作为目标类型)。
    猜你喜欢
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多