How can I obtain ObjectSet from Entity-Framewor

2020-06-17 03:51发布

问题:

(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);

回答1:

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);


回答2:

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);


回答3:

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.