How to ignore all properties that are marked as virtual

前端 未结 5 2123
误落风尘
误落风尘 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:13

    in case you wanna do it without needing to configure a second instance of automapper :

    public static class ClearNavigationExtension
    {
        public static void ClearNavigation(this object entity)
        {
            var type = entity.GetType();
    
            foreach (var property in type.GetProperties().Where(p => p.GetGetMethod().IsVirtual))
            {
                property.SetValue(entity, null);
            }
        }
    
        public static T ClearNavigation(this T entity)
        {
            var type = entity.GetType();
            var entityCopy = Mapper.Map(entity);
    
            foreach (var property in type.GetProperties().Where(p => p.GetGetMethod().IsVirtual))
            {
                property.SetValue(entityCopy, null);
            }
    
            return entityCopy;
        }
    
    }
    

提交回复
热议问题