我怎样才能获得的ObjectSet< T>从实体框架在运行时,其中T是动态的? [英] How can I obtain ObjectSet<T> from Entity-Framework at runtime where T is dynamic?

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

问题描述

(注意,下面的code只是例子,请不要对为什么这是必要的评论。我想AP preciate的是一个明确的答案或NO,就像如果可能的话又如何?如果不是,也没关系。如果问题是含糊不清,让我也知道,谢谢!)

例如,我可以得到的ObjectSet< T >如下:

 对象集<用户> USERSET = dbContext.CreateObjectSet<用户>();
对象集<类别> categorySet = dbContext.CreateObjectSet<类别>();

上面的code工作好。不过,我需要的实体表是动态的,所以我可以类型之间进行切换。类似下面。

  //变种类型= ty​​peof运算(用户);
VAR类型= ty​​peof运算(类别);
对象<&型GT;对象集= dbContext.CreateObjectSet<&型GT;();

不过,code以上将无法编译。


我想是一样的东西,或任何类似:

  //字符串tableName值=用户;
字符串tableName值=分类;
对象集对象集= dbContext.GetObjectSetByTableName(表名);


解决方案

你能在这里使用的示例中的如何使用反射来调用泛型方法?

  VAR类型= ty​​peof运算(类别); //或Type.GetType(类别),如果你有一个字符串
VaR方法= dbContext.GetType.GetMethod(CreateObjectSet);
变种通用= method.MakeGenericMethod(类型);
generic.Invoke(的DbContext,NULL);

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

解决方案

Can you use the example here in How to use reflection to call 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);

这篇关于我怎样才能获得的ObjectSet&LT; T&GT;从实体框架在运行时,其中T是动态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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