How to ignore all properties that are marked as virtual

前端 未结 5 2134
误落风尘
误落风尘 2020-12-29 13:33

I am using virtual keyword for some of my properties for EF lazy loading. I have a case in which all properties in my models that are marked as virtual

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-29 14:03

    inquisitive's answer works fine, but it can be augmented for real life usage, when some mappings are performed from data models to service models and virtual members from source type should be ignored.

    Also, if the type implements some interface, those properties will appear as virtual, so !IsFinal condition must be added to remove these false positive virtual properties.

    public static class AutoMapperExtensions
    {
        public static IMappingExpression IgnoreAllDestinationVirtual(this IMappingExpression expression)
        {
            var desType = typeof(TDestination);
            foreach (var property in desType.GetProperties().Where(p => p.GetGetMethod().IsVirtual && !p.GetGetMethod().IsFinal))
            {
                expression.ForMember(property.Name, opt => opt.Ignore());
            }
    
            return expression;
        }
    
        public static IMappingExpression IgnoreAllSourceVirtual(this IMappingExpression expression)
        {
            var srcType = typeof(TSource);
            foreach (var property in srcType.GetProperties().Where(p => p.GetGetMethod().IsVirtual && !p.GetGetMethod().IsFinal))
            {
                expression.ForSourceMember(property.Name, opt => opt.Ignore());
            }
    
            return expression;
        }
    }
    

提交回复
热议问题