How can I get an ObjectSet <T> from the Entity-Framework at runtime, where T is dynamic?
(Please note that the code below is just examples. Please do not comment on why this is necessary. I would appreciate a final answer of "YES" or "NO", for example, if this is possible, then how? If it is not . If the question is vague, let me know as well. Thank you!)
Example: I can get an ObjectSet <T> below:
ObjectSet<Users> userSet = dbContext.CreateObjectSet<Users>(); ObjectSet<Categories> categorySet = dbContext.CreateObjectSet<Categories>(); The above code is working fine. 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 above code will not compile.
[EDIT:] I would like something like or something like this:
//string tableName = "Users"; string tableName = "Categories"; ObjectSet objectSet = dbContext.GetObjectSetByTableName(tablename); Can you use the example here in How to use reflection to invoke 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); This works for me with the following settings for the above suggestions:
var type = Type.GetType(myTypeName); var method = _ctx.GetType().GetMethod("CreateObjectSet", Type.EmptyTypes); var generic = method.MakeGenericMethod(type); dynamic objectSet = generic.Invoke(_ctx, null); I found the answer here, http://geekswithblogs.net/seanfao/archive/2009/12/03/136680.aspx . This is very good because it eliminates the presence of multiple repository objects for each table displayed by EF, in particular for mundane operations such as CRUD, which is exactly what I was looking for.