2014-03-13 17 views
3

我正在尋找一種方法來動態/以編程方式更改列名稱和字段名稱;使用實體框架從動態/編程命名的列名稱獲取字段

爲:

string iLoadProfileValue = "ColumnName"; 

string lastCol = DatabaseFunctions.DatabaseClient 
.tbl_MeterLoadProfile 
.OrderByDescending(a => a.MeterReadDate) 
.FirstOrDefault(a => a.MeterID == meterID).iLoadProfileValue; 

我會編程修改iLoadProfileValue的價值。 我想獲得該列的值爲lastCol變量。

怎麼辦?

非常感謝。

完成:

最後一種情況是這樣的: 多虧了thepirat000Dismissile

string iLoadProfileValue = "MeterReadDate"; 
var myEntity = DatabaseFunctions.DatabaseClient.tbl_MeterLoadProfile.OrderByDescending(a => a.MeterReadDate).FirstOrDefault(a => a.MeterID == 6); 

if (myEntity != null) 
{ 
    var properties = myEntity.GetType().GetProperty(iLoadProfileValue); 
    object value = properties.GetValue(myEntity); 
} 
+0

爲什麼在_iLoadProfileValue_?上使用_i_前綴。只是問問。 – thepirat000

+0

只是一種習慣... –

+2

這是一個壞習慣:)。從_i_開始,意味着該變量是一個int。 – thepirat000

回答

6

你可以使用反射來獲取屬性的列表。查看System.Type上的GetProperties()方法。

http://msdn.microsoft.com/en-us/library/aky14axb(v=vs.110).aspx

public PropertyInfo[] GetProperties() 

然後,您可以使用LINQ發現maches一個你想要的屬性:

var myEntity = DatabaseFunctions.DatabaseClient 
    .tbl_MeterLoadProfile 
    .OrderByDescending(a => a.MeterReadDate) 
    .FirstOrDefault(a => a.MeterID == meterID); 

if(myEntity != null) { 
    var properties = myEntity.GetType().GetProperties(); 

    // iterate through the list of public properties or query to find the one you want 
    // for this example I will just get the first property, and use it to get the value: 
    var firstProperty = properties.FirstOrDefault(); 

    // get the value, it will be an object so you might need to cast it 
    object value = firstProperty.GetValue(myEntity); 
} 

由於thepirat000在評論中指出的,如果你只關心一個財產,您可以調用方法GetProperty(string name)而不是GetProperties()。如果你只關心一個屬性,而且你沒有反映實體中的所有列,這可能會更有效率。

+0

感謝您的快速回復。 http://prntscr.com/30ej8f我嘗試過,並得到這樣的。我怎樣才能用變量選擇數值? –

+0

PropertyInfo有一個名爲GetValue(object)的方法,該方法將需要獲取值的實例作爲參數。我編輯了帖子以顯示這一點。 http://msdn.microsoft.com/en-us/library/hh194385(v=vs.110).aspx – Dismissile

+1

您可能不需要使用_GetProperties()_獲取所有屬性,只需調用_GetProperty( iLoadProfileValue)_來獲取屬性。 – thepirat000