首页 > 解决方案 > Automapper 查找未映射的属性

问题描述

使用 Automapper 进行项目,只是将 2 个对象相互映射,没什么特别的。我必须有一些配置不正确,因为 AutoMapper 一直说有未映射的属性。
这是 AutoMapper 配置。

var mapperConfig = new MapperConfiguration(cfg => {cfg.CreateMap<SrcObj, DestObj>()
                .ForMember(dest => dest.Level, opt => opt.MapFrom(src => src.lvl));}
mapperConfig.AssertConfigurationIsValid();

对象

public  class SrcObj
{
    public int Id { get; set; }

    public int ParentNode { get; set; }

    public string Controller { get; set; }

    public string Action { get; set; }

    public string DisplayName { get; set; }

    public string Description { get; set; }

    public bool? IsActive { get; set; }

    public string AreaName { get; set; }

    public int? DisplayOrder { get; set; }

    public Int64 Type{ get; set; }

    public int lvl { get; set; }
}

目标对象

public  class DestObj
{
    public int Id { get; set; }

    public int ParentNode { get; set; }

    public string Controller { get; set; }

    public string Action { get; set; }

    public string DisplayName { get; set; }

    public string Description { get; set; }

    public bool? IsActive { get; set; }

    public string AreaName { get; set; }

    public int? DisplayOrder { get; set; }

    public Int64 Type{ get; set; }

    public int Level { get; set; }
}

和实施:

var items  = await _context.Database.SqlQuery<SrcObj>($"EXEC spGenerateMenu {app1}").ToListAsync();
var rslt = _mapper.Map<DestObj>(items);

和错误:

{"\n找到未映射的成员。查看下面的类型和成员。\n添加自定义映射表达式...}

该错误实际上列出了 DestObj 的每个成员。不知道我错过了什么。可能很简单

标签: c#.netentity-frameworkmodel-view-controllerautomapper

解决方案


因为您的来源是 a List,所以您还需要将其映射到 a List

var rslt = _mapper.Map<List<DestObj>>(items);

推荐阅读