【问题标题】:Automapper: Missing type map configuration .NET Web APIAutomapper:缺少类型映射配置 .NET Web API
【发布时间】:2021-11-17 01:23:57
【问题描述】:

我目前正在使用 .NET Web Api 来获取基于国家/地区的县列表。 在尝试获取县时,我收到“Automapper:缺少类型映射配置或不支持的映射”异常。

我的域类是:

 public class County
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string CountryId { get; set; }

        public virtual Country Country { get; set; }
        public virtual IList<City> City { get; set; }
    }

我的 DTO 是

 public class CountyResponse
    {
        public string Id { get; set; }
        public string Name { get; set; }
        public string CountryId { get; set; }
    }

映射配置文件:

public class CountyProfile : Profile
    {
        public CountyProfile()
        {
            CreateMap<CountyResponse, County>().ReverseMap();
        }
    }

我的服务类 GetAllLMethod:

 public async Task<Result<List<CountyResponse>>> GetAllAsync()
        {
            var counties = _context.Counties.ToListAsync();
            var mappedCounties = _mapper.Map<List<CountyResponse>>(counties);
            return await Result<List<CountyResponse>>.SuccessAsync(mappedCounties);
        }

构建正常,并且我的 Country 域映射完全相同 (1:1)。 然而,一个有效,而这个,在尝试访问 Get Endpoint 时,我收到了这个错误。 知道这里有什么问题吗? (服务已注册 - 我正在使用以下内容注入它们:

 public static void AddInfrastructureMappings(this IServiceCollection services)
        {
            services.AddAutoMapper(Assembly.GetExecutingAssembly());
        }

【问题讨论】:

    标签: c# .net api mapping automapper


    【解决方案1】:

    您正在将任务(ToListAsync 的结果)映射到失败的 DTO 列表。您需要等待您的查询,以便获得任务的结果,然后映射将正常工作

            var counties = await _context.Counties.ToListAsync();
            var mappedCounties = _mapper.Map<List<CountyResponse>>(counties);
    

    【讨论】:

    • 该死的!就这么简单……我说这与国家案是 1:1 的……好吧,那个人在那里等待!
    • 是的,有时我们会忽略一些显而易见的事情。如果对你有帮助,请标记答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2018-11-15
    • 2017-03-12
    • 2019-03-01
    • 2017-04-16
    • 2015-09-22
    相关资源
    最近更新 更多