(注意,下面的代码只是示例。请不要评论为什么这是必要的。我希望得到是或否的明确答案,如果可能,那么如何?如果不是,也没关系。如果问题含糊不清也让我知道。谢谢!)

例如,我可以在下面获得 ObjectSet:

ObjectSet<Users> userSet = dbContext.CreateObjectSet<Users>();
ObjectSet<Categories> categorySet = dbContext.CreateObjectSet<Categories>();

上面的代码工作正常。但是,我需要实体表是动态的,以便我可以在类型之间切换。像下面这样的东西。
//var type = typeof(Users);
var type = typeof(Categories);
Object<type> objectSet = dbContext.CreateObjectSet<type>();

但是上面的代码不会编译。

[编辑:]
我想要的是类似的东西,或者类似的东西:
//string tableName = "Users";
string tableName = "Categories";
ObjectSet objectSet = dbContext.GetObjectSetByTableName(tablename);

最佳答案

你能在 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);

关于asp.net - 如何在 T 是动态的运行时从 Entity Framework 获取 ObjectSet<T>?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7356232/

10-10 02:34