如何将long映射到IList <long>

时间:2019-01-16 07:45:14

标签: c# asp.net-core automapper

我有两个类,分别是 AccountSubscription AccountSubscriptionDto 。 我需要将“ AccountNumber”映射到“ AccountList”,作为AccontNumbers(IList)的集合。

public class AccountSubscription : BaseEntity
{
    [Required]
    public int CustomerNumber { get; set; }

    [Required]
    public long AccountNumber { get; set; }
}

public class AccountSubscriptionDto : BaseDto
{
    [Required]
    public int CustomerNumber { get; set; }

    [Required]
    public IList<long> AccountList { get; set; }

}

这是我将AccountNumber映射到AccountList的操作。

AutoMapperProfile.cs

    CreateMap<IList<AccountSubscription>, IList<AccountSubscriptionDto>> ()
        .ConstructUsing(list => list.GroupBy(g => new { g.CustomerNumber })
            .Select(s => new AccountSubscriptionDto
            {
                CustomerNumber = s.Key.CustomerNumber,
                AccountList = s.Select(t => t.AccountNumber).ToList()
            }).ToList()
        );

当我运行应用程序并使用get AccountSubscription方法时,出现此错误:

"error": "Error mapping types.

Mapping types:
PagedList`1 -> IEnumerable`1

WestCore.Shared.Collections.Pagination.PagedList`1[[WestCore.Domain.Entities.PCsbins.AccountSubscription, WestCore.Domain, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] -> System.Collections.Generic.IEnumerable`1[[WestCore.AppCore.Models.PCsbins.Account.AccountSubscriptionDto, WestCore.AppCore, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]"

编辑:这是我如何在应用程序中调用映射器,

return DomainResult<IPagedList<AccountSubscriptionDto>>
.Success(_mapper.Map<IPagedList<AccountSubscriptionDto>>(await _repository.
GetPagedListAsync(pageIndex, pageSize, cancellationToken: ctx)));

1 个答案:

答案 0 :(得分:1)

您配置了CreateMap<IList<AccountSubscription>, IList<AccountSubscriptionDto>>,但您需要_mapper.Map<IPagedList<AccountSubscriptionDto>>

尝试像

那样配置CreateMap<IPagedList<AccountSubscription>, IPagedList<AccountSubscriptionDto>>
CreateMap<IPagedList<AccountSubscription>, IPagedList<AccountSubscriptionDto>>()
    .ConstructUsing(source => source.Items.GroupBy(g => new { g.CustomerNumber })
        .Select(s => new AccountSubscriptionDto
        {
            CustomerNumber = s.Key.CustomerNumber,
            AccountList = s.Select(t => t.AccountNumber).ToList()
        }).ToPagedList(source.PageIndex, source.PageSize, source.IndexFrom)
    );

但是,通过这种方式,页面大小将因您对源数据进行分组而发生变化。

通常,您应按ToPagedList之前的源数据进行分组。您可以先考虑对查询AccountSubscription进行分组,然后再调用ToPagedList