AutoMapper:“忽略其余部分"? [英] AutoMapper: "Ignore the rest"?

查看:38
本文介绍了AutoMapper:“忽略其余部分"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法告诉 AutoMapper 忽略除显式映射的属性之外的所有属性?

Is there a way to tell AutoMapper to ignore all of the properties except the ones which are mapped explicitly?

我有可能从外部更改的外部 DTO 类,我想避免明确指定要忽略的每个属性,因为在尝试将它们映射到我自己的对象时添加新属性会破坏功能(导致异常).

I have external DTO classes which are likely to change from the outside and I want to avoid specifying each property to be ignored explicitly, since adding new properties will break the functionality (cause exceptions) when trying to map them into my own objects.

推荐答案

这是我编写的一个扩展方法,它忽略目标上所有不存在的属性.不确定它是否仍然有用,因为这个问题已经两年多了,但我遇到了同样的问题,不得不添加大量手动忽略调用.

This is an extension method I wrote that ignores all non existing properties on the destination. Not sure if it will still be useful as the question is more than two years old, but I ran into the same issue having to add a lot of manual Ignore calls.

public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>
(this IMappingExpression<TSource, TDestination> expression)
{
    var flags = BindingFlags.Public | BindingFlags.Instance;
    var sourceType = typeof (TSource);
    var destinationProperties = typeof (TDestination).GetProperties(flags);

    foreach (var property in destinationProperties)
    {
        if (sourceType.GetProperty(property.Name, flags) == null)
        {
            expression.ForMember(property.Name, opt => opt.Ignore());
        }
    }
    return expression;
}

用法:

Mapper.CreateMap<SourceType, DestinationType>()
                .IgnoreAllNonExisting();

UPDATE:如果您有自定义映射,这显然无法正常工作,因为它会覆盖它们.我想如果先调用 IgnoreAllNonExisting 然后再调用自定义映射,它仍然可以工作.

UPDATE: Apparently this does not work correctly if you have custom mappings because it overwrites them. I guess it could still work if call IgnoreAllNonExisting first and then the custom mappings later.

schdr 有一个解决方案(作为这个问题的答案),它使用 Mapper.GetAllTypeMaps() 找出哪些属性未映射并自动忽略它们.对我来说似乎是一个更强大的解决方案.

schdr has a solution (as an answer to this question) which uses Mapper.GetAllTypeMaps() to find out which properties are unmapped and auto ignore them. Seems like a more robust solution to me.

这篇关于AutoMapper:“忽略其余部分"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆