Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I obtain ObjectSet<T> from Entity-Framework at runtime where T is dynamic?

(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);
like image 302
Ronald Avatar asked Sep 09 '11 01:09

Ronald


2 Answers

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);
like image 91
Stubby Avatar answered Sep 17 '22 23:09

Stubby


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);
like image 28
Preet Sangha Avatar answered Sep 18 '22 23:09

Preet Sangha