How to configure Automapper to automatically ignore properties with ReadOnly attribute?

后端 未结 3 558
感情败类
感情败类 2020-12-09 16:04

Context:

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

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

    pu         


        
3条回答
  •  盖世英雄少女心
    2020-12-09 16:36

    Write Extension Method as shown below:

    public static class IgnoreReadOnlyExtensions
    {
        public static IMappingExpression IgnoreReadOnly(
                   this IMappingExpression 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;
        }
    }
    

    To call extension method:

    Mapper.CreateMap().IgnoreReadOnly();

提交回复
热议问题