2013-04-03 60 views
0

我想獲取實體框架中的表數據模型的屬性名稱。 我有這樣的代碼獲取使用字符串的表的屬性名稱

var properties = context.GetType().GetProperties(BindingFlags.DeclaredOnly | 
             BindingFlags.Public | 
             BindingFlags.Instance); 

所有我想要的是有一個像以具有定義表模型一個字符串變量下面的方法驗證碼:

MyMethod (string category) 
{ 
    var properties = "category".GetType().GetProperties(BindingFlags.DeclaredOnly | 
            BindingFlags.Public | 
            BindingFlags.Instance); 
    ...... 
    ...... 

} 

是它可能?提前Thanx

回答

1

您可以使用Assembly.GetType(string)方法來執行此操作。您的代碼會是這個樣子:不能訪問非靜態方法「:

// Don't forget to null-check the result of GetType before using it! 
// You will also need to specify the correct assembly. I've assumed 
// that MyClass is defined in the current executing assembly. 
var properties = Assembly.GetExecutingAssembly().GetType("My.NameSpace.MyClass"). 
    GetProperties(
     BindingFlags.DeclaredOnly | 
     BindingFlags.Public | 
     BindingFlags.Instance); 

您還可以使用Type.GetType(string)

var properties = Type.GetType("My.NameSpace.MyClass"). 
    GetProperties(
     BindingFlags.DeclaredOnly | 
     BindingFlags.Public | 
     BindingFlags.Instance); 
+0

謝謝你的回答,但是我使用上面的代碼時出現此錯誤GetType'在靜態上下文 –

+0

我已經更新了我的答案,並提供了一個解決方法,另一種方法(Type.GetType方法可能更簡單一些) –

+0

太好了!非常感謝。 –