2011-09-09 24 views
7

(請注意,下面的代碼僅僅是一些例子,請不要評論爲什麼這是必要的,我很感謝YES或NO的明確答案,如果可能的話,那麼如何?如果不是,那也不錯。問題是含糊不清,讓我也知道,謝謝)如何在T是動態的運行時從Entity-Framework獲得ObjectSet <T>?

例如,我可以得到下面的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); 
+0

的可能重複(http://stackoverflow.com/questions/ 232535/how-to-use-reflection-to-call-generic-method) – nawfal

回答

4

你能在這裏使用的例子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); 
0

我已經在這裏找到了答案,http://geekswithblogs.net/seanfao/archive/2009/12/03/136680.aspx。這非常好,因爲它消除了由EF映射的每個表都有多個存儲庫對象,特別是對於像CRUD這樣的普通操作,這正是我所尋找的。

+1

這就是爲什麼這絕對是OT:「請不要評論爲什麼這是必要的。」如果你剛纔描述了爲什麼有必要,你可以立即得到答案。此外,請檢查此:http://stackoverflow.com/questions/5625746/generic-repository-with-ef-4-1-what-is-the-point/5626884#5626884通用資源庫是不正確的模式 - 它只是有用的一個特定存儲庫的基地:http://stackoverflow.com/questions/7110981/the-repository-itself-is-not-usually-tested相關的問題是關於DbContext API,但它與ObjectContext API相同。 –

+0

這是一個非常好的鏈接。謝謝。 – Ronald

6

我有這個工作有以下TWEAK以上建議:?如何使用反射來調用通用方法]

var type = Type.GetType(myTypeName); 
var method = _ctx.GetType().GetMethod("CreateObjectSet", Type.EmptyTypes); 
var generic = method.MakeGenericMethod(type); 
dynamic objectSet = generic.Invoke(_ctx, null); 
相關問題