How to recursively Iterate over properties of an Entity

后端 未结 1 1774
无人及你
无人及你 2020-12-21 16:52

Suppose this is what I have in my database


table Ancestor (  
  idAncestor int not null,  
  name varchar(20) not null,  
)  

table Descendant (  
  idDes         


        
相关标签:
1条回答
  • 2020-12-21 17:36

    This should be a crude version of what you're looking for:

    private static void recurseAndPrintProperties(Object ObjectToRecurse) {
       foreach (PropertyInfo pi in ObjectToRecurse.GetType().GetProperties()) {
           if ((pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(EntityCollection<>))) {
               IEnumerable collection = (IEnumerable)pi.GetValue(ObjectToRecurse, null);
    
               foreach (object val in collection)
                   recurseAndPrintProperties(val);
           } else {
                if (pi.PropertyType == typeof(Descendant)) {
                    Descendant actualDescendant = (Descendant)pi.GetValue(ObjectToRecurse, null);
                    Console.WriteLine(actualDescendant.idDescendant + " - " + actualDescendant.Name);
                } else
                    Console.WriteLine(pi.Name + "  -  " + pi.GetValue(ObjectToRecurse, null));
           }
       }
    }
    

    EDIT

    This code came from some code I had previously played around with for cloning entities. Here it is (you might have to modify it to also take into consideration not duplicating your properties thar are mapped to primary keys)

        public static T CloneEntity<T>(T Obj) where T : EntityObject, new() {
            T Clone = new T();
    
            Type typeToClone = Obj.GetType();
            Type[] BadGenericTypes = new Type[] { typeof(EntityCollection<>), typeof(EntityReference<>) };
            Type[] BadTypes = new Type[] { typeof(System.Data.EntityKey) };
    
            foreach (PropertyInfo pi in typeToClone.GetProperties().Where(p => p.CanWrite)) {
                if (pi.PropertyType.IsGenericType && BadGenericTypes.Contains(pi.PropertyType.GetGenericTypeDefinition())
                    || (BadTypes.Contains(pi.PropertyType))
                    || (pi.Name.Equals(Extension.GetPropertyName(() => new FMVHistory().FMVHistoryId), StringComparison.CurrentCultureIgnoreCase)))
                    continue;
    
                pi.SetValue(Clone, pi.GetValue(Obj, null), null);
            }
            return Clone;
        }
    
    0 讨论(0)
提交回复
热议问题