I do have a problem with EF Core. I need a Instance of a DBSet<> without knowing the Type until runtime and method is called. I need this Instance to add Include Statements dynamically and finally load the information from DB.
I do get an object, which seems to be correct since the debugger recognizes the DBSet of the type i need, but I cannot cast it, in order to work with the methods and properties.
In addition, it was not possible for me to find a solution in the forums, which is why I am reporting here
I already tried to call the generic method at runtime using reflection, but failed, since the result is of has the type object. Is there a way to cast the object to a DBSet of my dynamic type ?
Here is my current attempt to implement the whole thing:
public static DbSet<T> GetDbSet<T>(DbContext _context) where T : class
=>(DbSet<T>)_context.GetType().GetMethod("Set", types: Type.EmptyTypes).MakeGenericMethod(typeof(T)).Invoke(_context, null);
/* Return Query to fetch all Models from Database */
private void GetQuery(Type rootType, List<ImportMappingModel> mapping, DbContext context)
{
var MethodInfo = this.GetType().GetMethod("GetDbSet");
var generic = MethodInfo.MakeGenericMethod(rootType);
var dbSet = generic.Invoke(null,new object?[]{context} );
}
Thank you very much for your help Regards Luis