【问题标题】:Ignore destination member in AutoMapper not working忽略 AutoMapper 中的目标成员不起作用
【发布时间】:2021-09-13 17:17:20
【问题描述】:

我有以下忽略 Id 字段的简单类和映射。
我注意到的是,当我从 Eto/Dto 映射到实体时,.Ignore() 不起作用,我不知道它背后的原因。

我使用的是最新的 ABP 4.4。

public class Country : Entity<string>
{
    public Country() {}
    public Country(string id) { Id = id; }
}

public class CountryDto : EntityDto<string> { }

CreateMap<Country, CountryDto>().Ignore(x => x.Id); // id ignored
CreateMap<CountryDto, Country>().Ignore(x => x.Id); // id not ignored

在我的测试中映射代码:

var country1 = new Country("XX");
var dto1 = ObjectMapper.Map<Country, CountryDto>(country1);
        
var dto2 = new CountryDto() { Id = "XX" };
var country2 = ObjectMapper.Map<CountryDto, Country>(dto2);

我也尝试过忽略正常的 AutoMapper 长格式,而不是 ABP 的 Ignore 扩展名。

【问题讨论】:

    标签: c# automapper abp


    【解决方案1】:

    AutoMapper 根据源成员映射到目标构造函数。

    有几种方法可以在目标构造函数中忽略id

    1. id构造函数参数映射到null
       CreateMap<Country, CountryDto>().Ignore(x => x.Id);
    // CreateMap<CountryDto, Country>().Ignore(x => x.Id);
       CreateMap<CountryDto, Country>().Ignore(x => x.Id).ForCtorParam("id", opt => opt.MapFrom(src => (string)null));
    
    1. 指定ConstructUsing
       CreateMap<Country, CountryDto>().Ignore(x => x.Id);
    // CreateMap<CountryDto, Country>().Ignore(x => x.Id);
       CreateMap<CountryDto, Country>().Ignore(x => x.Id).ConstructUsing(src => new Country());
    
    1. Country 构造函数中重命名id 参数。
    // public Country(string id) { Id = id; }
       public Country(string countryId) { Id = countryId; }
    
    1. DisableConstructorMapping 适用于所有地图。
    DisableConstructorMapping(); // Add this
    CreateMap<Country, CountryDto>().Ignore(x => x.Id);
    CreateMap<CountryDto, Country>().Ignore(x => x.Id);
    
    1. 排除带有任何名为id 的参数的构造函数。
    ShouldUseConstructor = ci => !ci.GetParameters().Any(p => p.Name == "id"); // Add this
    CreateMap<Country, CountryDto>().Ignore(x => x.Id);
    CreateMap<CountryDto, Country>().Ignore(x => x.Id);
    

    参考:https://docs.automapper.org/en/v10.1.1/Construction.html

    【讨论】:

    • 感谢@aaron!我试过 #1 和 #2 都有效。仍然不太明白为什么忽略实体对 eto/dto 有效,但反之则不然。从本质上讲,它仍然是 dest 的来源。会记住这一点=)
    • 它适用于属性映射,但不适用于构造函数映射。如果您在 Eto/Dto 中添加了带有 id 参数的构造函数,那么它也不会起作用。
    猜你喜欢
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多