lundi 23 décembre 2019

.NET C# - How to use variable generic type in a recursive call?

I am coding a generic function that receives any entity class, accesses the database based on the class received and return an object filled with the contents returned from the database. Before someone asks, yes I am coding my own Entity Framework (just for fun!). What I already coded works if the class doesn't contain another class type. If the class contains another class inside I am trying to use recursive call to retrieve the object. In this case the generic type is changing and here is the point, the compiler doesn't accept a variable generic type. For example, suppose I have these 2 classes:

namespace Entities {
    public class Order {
        public int?Id { get; protected set; }
        public DateTime Moment { get; set; }
        public Client Client { get; set; }
    }

    public class Client {
        public int?Id { get; protected set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
}

The generic function is: (simplified here and without the database access)

public static T GetById<T>(int? id) {
    object obj = Activator.CreateInstance(typeof(T));
    foreach (PropertyInfo prop in obj.GetType().GetProperties()) {
        if (prop.PropertyType.Namespace == "Entities") {
            int? idParent = n1; //where n1 is a value returned previously from DB
            Type objType = prop.PropertyType;
            prop.SetValue(obj, GetById<objType>(idParent)); //Compile error! "'objType' is a variable but is used like a type"
        }
        prop.SetValue(obj, n2); //where n2 is a value returned previously from DB
    }
    return (T)obj;
}

It doesn't compile returning "'objType' is a variable but is used like a type". The code in the main program would have this line:

Order ord = GetById<Order>(1);

In this first call the type is known (Order) and the function works (without recursive call) returning the "Order" object but without the "Client" object. To retrive the "Client" object I need to call the function again (recursive call) but now the returned Type is unknown at compile time.

Does anyone have any suggestion?





Aucun commentaire:

Enregistrer un commentaire