如何获取ObjectSet< T>在运行时的实体框架T是动态的? [英] How can I obtain ObjectSet<T> from Entity-Framework at runtime where T is dynamic?

查看:88
本文介绍了如何获取ObjectSet< T>在运行时的实体框架T是动态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(注意,下面的代码只是例子,请不要评论为什么这是必要的,我会感谢一个确定的答案YES或NO,如果可能的话,如果不是很好。

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

示例,我可以得到ObjectSet 下面的

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.


我想要的是或类似的东西:

What I'd like is something like, or anything similar:

//string tableName = "Users";
string tableName = "Categories";
ObjectSet objectSet = dbContext.GetObjectSetByTableName(tablename);


推荐答案

你可以在如何使用反射来调用通用方法?

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

这篇关于如何获取ObjectSet&lt; T&gt;在运行时的实体框架T是动态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆