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

编程入门 行业动态 更新时间:2024-10-28 08:21:16
本文介绍了使用Automapper时如何忽略特定类型的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

让我们假设我有两种类型:

Let's suppose that I have two types:

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的属性.这是因为我正在使用反射来遍历所有这些对象,并在它们上进行一些自定义映射.

I want to map between these two types, but ignoring all the properties that have a TypeToIgnore. This is because I am iterating through all of them using reflection and make some custom mappings on them.

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

Within a class which derives from Profile, I could add an Ignore for each member that I don't want to be mapped, like this:

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

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

Or I could use the IgnoreMapAttribute on the properties to be ignored, but considering that on the production code, I have plenty of them, is there a much easier way to ignore some specific types at all?

推荐答案

您可以在配置中使用ShouldMapProperty:

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

此官方文档位于此处.真正由您发出的原始功能请求.

Official docs on this here. Original feature request by yours truly.

更多推荐

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

本文发布于:2023-11-09 10:48:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1572170.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   类型   Automapper

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!