7

(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);
Ronald
  • 1,508
  • 4
  • 18
  • 33
  • possible duplicate of [How to use reflection to call generic Method?](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) – nawfal Jan 17 '14 at 15:09

3 Answers3

6

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);
Stubby
  • 61
  • 1
  • 1
4

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);
Community
  • 1
  • 1
Preet Sangha
  • 61,126
  • 17
  • 134
  • 202
0

I have found the answer here, http://geekswithblogs.net/seanfao/archive/2009/12/03/136680.aspx. This is very good because it eliminates having multiple repository objects for each table mapped by EF particularly for mundane operations like CRUD, which is exactly what I was looking for.

Ronald
  • 1,508
  • 4
  • 18
  • 33
  • 1
    That is why this was absolutely OT: "Please don't comment on the why this is necessary." If you just described why it is necessary you could have that answer immediately. Also check this: http://stackoverflow.com/questions/5625746/generic-repository-with-ef-4-1-what-is-the-point/5626884#5626884 Generic repository is incorrect pattern - it is useful only as a base for specific repository: http://stackoverflow.com/questions/7110981/the-repository-itself-is-not-usually-tested Related questions are about DbContext API but it is same with ObjectContext API. – Ladislav Mrnka Sep 09 '11 at 06:35