如何将Automapper配置为自动忽略具有ReadOnly属性的属性? [英] How to configure Automapper to automatically ignore properties with ReadOnly attribute?

查看:184
本文介绍了如何将Automapper配置为自动忽略具有ReadOnly属性的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说我有以下目的地"课程:

Let's say I have the following "destination" class:

public class Destination
{
    public String WritableProperty { get; set; }

    public String ReadOnlyProperty { get; set; }
}

和一个在其属性之一上具有ReadOnly属性的源"类:

and a "source" class with the ReadOnly attribute on one of it's properties:

public class Source
{
    public String WritableProperty { get; set; }

    [ReadOnly(true)]
    public String ReadOnlyProperty { get; set; }
}

这很明显,但要明确:我将以以下方式将Source类映射到Destination类:

It's obvious, but to be clear: I am going to map from Source class to Destination class in the following way:

Mapper.Map(source, destination);

问题:

有哪些方法可以配置Automapper以自动忽略具有ReadOnly(true)属性的属性?

Problem:

What are the ways to configure Automapper to automatically ignore property with ReadOnly(true) attribute?

我使用Automapper的Profile类进行配置.我不想弄脏具有Automapper特定属性的类.我不想为每个只读属性都配置Automapper,并以此方式导致大量重复.

I use Automapper's Profile classes for configuration. I don't want to dirty up classes with Automapper-specific attributes. I don't want to configure Automapper for every single read-only property and cause a lot of duplication by this way.

    [ReadOnly(true)]
    [IgnoreMap]
    public String ReadOnlyProperty { get; set; }

我不想弄乱具有特定于automapper的属性的类,并使其依赖于它.另外,我也不想与ReadOnly属性一起添加其他属性.

I don't want to dirty up classes with automapper-specific attributes and make it dependent from it. Also I don't want to add additional attribute along with ReadOnly attribute.

CreateMap<Source, Destination>()
.ForSourceMember(src => src.ReadOnlyProperty, opt => opt.Ignore())

这不是一种方法,因为它迫使我对各地的每个资产都这样做,而且还会造成很多重复.

It is not a way because it forces me to do that for every single property everywhere and also causes a lot of duplication.

推荐答案

编写扩展方法,如下所示:

public static class IgnoreReadOnlyExtensions
{
    public static IMappingExpression<TSource, TDestination> IgnoreReadOnly<TSource, TDestination>(
               this IMappingExpression<TSource, TDestination> expression)
    {
        var sourceType = typeof(TSource);

        foreach (var property in sourceType.GetProperties())
        {
            PropertyDescriptor descriptor = TypeDescriptor.GetProperties(sourceType)[property.Name];
            ReadOnlyAttribute attribute = (ReadOnlyAttribute) descriptor.Attributes[typeof(ReadOnlyAttribute)];
            if(attribute.IsReadOnly == true)
                expression.ForMember(property.Name, opt => opt.Ignore());
        }
        return expression;
    }
}

呼叫附加信息方法:

Mapper.CreateMap<ViewModel, DomainModel>().IgnoreReadOnly();

这篇关于如何将Automapper配置为自动忽略具有ReadOnly属性的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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