(Note, the code below are just examples. Please don't comment on the why this is necessary. I would appreciate a definitive answer of YES or NO, like if it is possible then how? If not it's fine too. If the question is vague let me know also. Thanks!)
Example, I can get ObjectSet<T> below:
ObjectSet<Users> userSet = dbContext.CreateObjectSet<Users>();
ObjectSet<Categories> categorySet = dbContext.CreateObjectSet<Categories>();
The code above works okay. However, I need the entity table to be dynamic so I can switch between types. Something like below.
//var type = typeof(Users);
var type = typeof(Categories);
Object<type> objectSet = dbContext.CreateObjectSet<type>();
But the code above will not compile.
[EDIT:] What I'd like is something like, or anything similar:
//string tableName = "Users";
string tableName = "Categories";
ObjectSet objectSet = dbContext.GetObjectSetByTableName(tablename);
I've got this working with the following tweak to the suggestions above:
var type = Type.GetType(myTypeName);
var method = _ctx.GetType().GetMethod("CreateObjectSet", Type.EmptyTypes);
var generic = method.MakeGenericMethod(type);
dynamic objectSet = generic.Invoke(_ctx, null);
Can you use the example here in How do I use reflection to call a generic method?
var type = typeof(Categories); // or Type.GetType("Categories") if you have a string
var method = dbContext.GetType.GetMethod("CreateObjectSet");
var generic = method.MakeGenericMethod(type);
generic.Invoke(dbContext, null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With