mercredi 14 avril 2021

How to traverse an unknown object of type T hierarchy with reflection, get all the class types, then add them an EF core DbContext with C#?

I am developing a generic function to use with EF core, The important one is setAddedState, I am not really interested in an EF Core work arounds but in how to send a generic tree recursively to this statement:

 context.Entry(entity).State = EntityState.Added; 

where entity is recursively obtained from an unknown object, that may contains lists of other objects and direct object descendants:

        public async Task<T> CreateGraph(T entity) {
            using (AppDbContext context = _contextFactory.CreateDbContext()) {
            setAddedState(context, entity);
            }
           return entity;
        }
        // this method does not work:
        private void setAddedState(AppDbContext context, object entity) {
           // entity object is the root of the tree, contains many sub objects and List<OtherObjects>
            context.Entry(entity).State = EntityState.Added;
            Console.WriteLine("entry added");
           foreach (FieldInfo fieldInfo in entity.GetType().GetFields())
           {
               Console.WriteLine($"prop name: {fieldInfo.Name}, prop type: {fieldInfo.FieldType.ToString()}");
               if (fieldInfo.FieldType == typeof(List<>)){
                   foreach(var item in fieldInfo.getValue())
                   {  
                      setAddedState(context, entity);
                   }

               }
               setAddedState(context, fieldInfo.GetValue(entity));
           }
        }

The idea is to traverse the object graph tree from the root and add it to EF core context object manually, the pre assumption is that all sub objects are already added with DbSet to dbContext is OK. Graph of objects looks like:

Class1 c = new Class1(){ //root object is added
     Prop1 = new Class2() { ...}, //Class2 should be added to dbContext.
     Prop2 = new List<Class3>{ ...}, // each item in class3 list should be added to dbContext
     Prop3 = "string" // value type is not to be added ofcourse
}

The point is not just for EF Core, but how to make a totally generic function and extract types for use in similar examples like the addition for EF core.





Aucun commentaire:

Enregistrer un commentaire