You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用AutoMapper映射对象列表时遇类型转换错误求助

问题详情

映射配置代码(MappingProfile.cs)

public class MappingProfile: Profile
{
    public 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=Cannot implicitly convert type 'System.Collections.Generic.List<Core.Application.Contracts.DTOs.GraphUserDeltaApiDto>' to 'System.Collections.Generic.List<Core.Domain.Entities.User>'

修改后的代码与新错误

修改后的代码:

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>)' has some invalid arguments
Source=System.Linq.Expressions

需求说明

已知AutoMapper会自动复制同名字段,当前源数据字段比目标多,需要解决映射报错问题。


解决建议
  1. 修正映射调用的泛型参数
    核心问题是搞反了AutoMapper映射的类型顺序:

    • 若使用Map<TDestination>(source)重载,直接指定目标类型即可:
      List<User> freshUsers = mapper.Map<List<User>>(graphDtoUsers);
      
    • 若要明确指定源和目标类型,注意泛型参数顺序为源在前,目标在后:
      List<User> freshUsers = mapper.Map<List<GraphUserDeltaApiDto>, List<User>>(graphDtoUsers);
      
  2. 确认源数据的实际类型
    检查graphClient.UserObjects的返回类型是否为List<GraphUserDeltaApiDto>或兼容的可枚举类型(如IEnumerable<GraphUserDeltaApiDto>)。如果是其他类型,先转换为可枚举集合再映射,AutoMapper支持直接将IEnumerable映射为List。

  3. 验证映射配置的有效性
    在应用启动时添加配置验证,提前发现映射规则的问题:

    mapper.ConfigurationProvider.AssertConfigurationIsValid();
    

    默认情况下多余的源字段会被AutoMapper忽略,无需额外配置;如果需要严格校验字段映射,可以在创建映射时添加ReverseMap().ForAllOtherMembers(opt => opt.Ignore())或者开启全局严格模式。


内容的提问来源于stack exchange,提问作者dot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 23:15:59