【问题标题】:How to ignore properties of a specific type when using Automapper?使用 Automapper 时如何忽略特定类型的属性?
【发布时间】:2019-02-19 17:05:26
【问题描述】:

假设我有两种类型:

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,但考虑到在生产代码中,我有很多,有没有更简单的方法来忽略某些特定类型?

【问题讨论】:

    标签: c# automapper


    【解决方案1】:

    您可以在配置中使用ShouldMapProperty

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

    here 上的官方文档。原创 feature request 真实出自你。

    【讨论】:

    • 这确实符合我的要求,这就是我将其标记为答案的原因,但我仍然希望它在调用cfg.AssertConfigurationIsValid();时不会引发异常@
    • 老实说,这不应该发生。你能发布另一个关于这个的问题吗?
    • 是的,我会回来的,我会在这里发表另一条评论,让你知道我做了,但现在我有点忙,抱歉 :)
    • 我刚打开another thread on this topic。非常感谢您的帮助!
    猜你喜欢
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 2011-06-26
    相关资源
    最近更新 更多