使用Automapper时如何忽略特定类型的属性?

2024-01-13

假设我有两种类型:

class Type1
{
    public int Prop1 { get; set; }
    public string Prop2 { get; set; }
    public string Prop3 { get; set; }
}

class Type2
{
    public int Prop1 { get; set; }
    public string Prop2 { get; set; }
    public TypeToIgnore Prop3 { get; set; }
}

我想在这两种类型之间进行映射,但忽略所有具有TypeToIgnore。这是因为我使用反射迭代所有这些,并在它们上进行一些自定义映射。

在派生自的类中Profile,我可以添加一个Ignore对于我不想映射的每个成员,如下所示:

CreateMap<Type2, Type1>().ForMember(x => x.Prop3, y => y.Ignore());

或者我可以使用IgnoreMapAttribute关于要忽略的属性,但考虑到在生产代码中,我有很多属性,是否有更简单的方法来忽略某些特定类型?


您可以使用ShouldMapProperty在你的配置中:

 cfg.ShouldMapProperty = p => p.PropertyType != typeof(string);

官方文档对此here https://docs.automapper.org/en/stable/Configuration.html?highlight=shouldmapproperty。原来的功能要求 https://github.com/AutoMapper/AutoMapper/issues/566真的是你的。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用Automapper时如何忽略特定类型的属性? 的相关文章

随机推荐