How to ignore all properties that are marked as virtual

前端 未结 5 2127
误落风尘
误落风尘 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条回答
  •  梦毁少年i
    2020-12-29 14:08

    You can create a mapping extension and use it:

    namespace MywebProject.Extensions.Mapping
    {
        public static class IgnoreVirtualExtensions
        {
            public static IMappingExpression
                   IgnoreAllVirtual(
                       this IMappingExpression expression)
            {
                var desType = typeof(TDestination);
                foreach (var property in desType.GetProperties().Where(p =>   
                                         p.GetGetMethod().IsVirtual))
                {
                    expression.ForMember(property.Name, opt => opt.Ignore());
                }
    
                return expression;
            }
        }
    }
    

    Usage :

    Mapper.CreateMap().IgnoreAllVirtual();
    

提交回复
热议问题