尝试使用自动映射器映射对象列表

问题描述 投票:0回答:1

我的 MappingProfile.cs 中有以下代码: 公共类 MappingProfile:配置文件 { 公共映射配置文件() {

        CreateMap<GraphUserDeltaApiDto, User>().ReverseMap();
    }

}

在我的代码中我这样做:

 graphClient.CheckforUserDeltas();
 var graphDtoUsers = graphClient.UserObjects;
 List<User> freshUsers = mapper.Map<List<GraphUserDeltaApiDto>>(graphDtoUsers);
                    

我得到的错误是:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
HResult=0x80131500 Message=无法隐式转换类型 'System.Collections.Generic.List' 到 'System.Collections.Generic.List'

我找到这篇文章:
使用 Automapper 映射列表

基于此,我尝试将我的逻辑更改为如下所示:

 var Users = mapper.Map(List<User>,List<GraphUserDeltaApiDto>>(graphDtoUsers);
                    var localSave = UpsertO3MWithLatestUserData(Users);

但现在我得到这个错误:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
  HResult=0x80131500
  Message=The best overloaded method match for 'AutoMapper.IMapperBase.Map<System.Collections.Generic.List<Core.Domain.Entities.User>,System.Collections.Generic.List<Core.Application.Contracts.DTOs.GraphUserDeltaApiDto>>(System.Collections.Generic.List<Core.Domain.Entities.User>)'

有一些无效的参数 来源=System.Linq.Expressions

我的理解是,任何具有相同名称的字段都将从源对象复制到目标对象。在我的例子中,源的数据比目的地多得多。
我不确定如何调试它。

任何提示将不胜感激。

c# automapper
1个回答
0
投票

您正在尝试将

List<GraphUserDeltaApiDto>
分配给
List<User>
,因为
mapper.Map<List<GraphUserDeltaApiDto>>(graphDtoUsers);
返回指定为模板参数的类型的值。

AutoMapper 中的

Map
方法具有下一个签名:

/// <summary>
/// Execute a mapping from the source object to a new destination object.
/// The source type is inferred from the source object.
/// </summary>
/// <typeparam name="TDestination">Destination type to create</typeparam>
/// <param name="source">Source object to map from</param>
/// <returns>Mapped destination object</returns>
TDestination Map<TDestination>(object source);

/// <summary>
/// Execute a mapping from the source object to a new destination object.
/// </summary>
/// <typeparam name="TSource">Source type to use, regardless of the runtime type</typeparam>
/// <typeparam name="TDestination">Destination type to create</typeparam>
/// <param name="source">Source object to map from</param>
/// <returns>Mapped destination object</returns>
TDestination Map<TSource, TDestination>(TSource source);

所以你必须在

Map<TDestination>
方法中使用你的目标类型而不是源类型:

graphClient.CheckforUserDeltas();
var graphDtoUsers = graphClient.UserObjects;
List<User> freshUsers = mapper.Map<List<User>>(graphDtoUsers);

如果使用

TDestination Map<TSource, TDestination>(TSource source)
方法,则必须使用源类型作为第一个泛型参数,目标类型作为第二个泛型参数:

 var users = mapper.Map<List<GraphUserDeltaApiDto>, List<User>>(graphDtoUsers);

此 кгду 不仅适用于集合,而且适用于 AutoMapper 中的所有转换,因为它使用相同的方法。

© www.soinside.com 2019 - 2024. All rights reserved.