【问题标题】:Automapper Custom configuration for members is only supported for top-level individual members on a typeAutomapper 成员的自定义配置仅支持类型上的顶级个人成员
【发布时间】:2020-04-10 20:29:37
【问题描述】:

我正在尝试映射从数据库中获得的结果,并且我有以下模型

public class ClientTest
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class ClientTestDto
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class ClientDbItem
{
    public ClientTest Client { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public int Id { get; set; }
    public string Value { get; set; }
}

和下面的映射

CreateMap<ClientTest, ClientTestDto>();

CreateMap<ClientDbItem, ClientTestDto>()
    .ForMember(dest => dest, opt => opt.MapFrom(src => src.Client));

当我运行软件时,我得到了

成员的自定义配置仅支持顶级 类型上的单个成员

如果我首先为 ClientTest 和 ClientTestDto 创建配置,为什么会发生这种情况?

【问题讨论】:

标签: c# .net .net-core automapper


【解决方案1】:

为此有一个特殊的 API,IncludeMembers。见here

【讨论】:

    【解决方案2】:

    当您尝试将顶级元素映射到构造函数时,也可能会出现此错误:

        .ForMember(dest => dest, opt => opt.MapFrom(
            src => new B1(src.Prop3, src.Prop4)));
    

    而不是将顶级元素 MEMBER 映射到构造函数(可以正常工作):

        .ForMember(dest => dest.MyProperty, opt => opt.MapFrom(
            src => new B1(src.Prop3, src.Prop4)));
    

    为避免这种情况,请使用 .ForCtorParam

    例子:

    CreateMap<Source, DestinationWithConstructor>()
    .ForCtorParam("code", opt => opt.MapFrom(src => src.Prop3))
    .ForCtorParam("text", opt => opt.MapFrom(src => src.Prop4))
    

    【讨论】:

      猜你喜欢
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-27
      • 2012-07-17
      • 2012-03-03
      相关资源
      最近更新 更多