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

查看:361
本文介绍了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();

更新:显然,这如果您有自定义映射,因为它会覆盖他们无法正常工作。我猜它仍然可以工作,如果呼叫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:&QUOT;忽略其余&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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