2016-03-24 34 views
1

讓我先介紹一下我已經搜索過這個問題並嘗試了很多東西,但我明顯錯過了一些簡單的東西(我認爲)。試圖在EF中使用變量在運行時替換字段名稱

我相信我的解決方案會涉及到反思,但我無法做到正確。

編輯: 更快的問題 - 我需要用字符串替換查詢結果的.fieldname。所以var value = stops.First().con_name;.con_name需要在運行時動態。

基本信息: 我正在創建從數據庫中生成自定義報告的功能,其中報告佈局存儲在列名稱,列位置和字段名稱的表中。

所以下面是一個非常簡單的報表中的數據:

record 1 
col_index - 17 
field_name - con_name 

record 2 
col_index - 18 
field_name- con_city 

我需要查詢一個表的要被包含在報告中記錄的集合稱爲stop_details

然後我想查詢一個名爲report_matrix的表,它將返回上面的記錄(我給出的兩個樣本記錄)。

然後我需要遍歷矩陣結果並根據數據創建列。

挑戰是在運行時替換field_name。 所以在下面的代碼在第一次運行,通過它將有var value = stops.First().con_name; .con_name將與.con_city等進行更換,第二次....

這裏是我的代碼:

 //get collection of stops for export 

     var stops = (from s in db.stop_details 
        where s.eCourier_export_flag == true 
        select s) 
        .ToArray(); 

     //pull in all the report format details 

     var reportLayout = (from r in db.report_matrix 
          where r.report_id == 1 
          select r) 
          .ToArray(); 

     //just do one line 

     foreach (var layoutElement in reportLayout) 
     {     
      // Select the PropertyInfo of the column. 
      PropertyInfo propertyInfo = 
       stops.First().GetType().GetProperty(layoutElement.field_name); 
      // name = stops.GetValue(propertyInfo, null).ToString(); 
      // HERE is where I need to replace .con_name with the field name from the query 
      var value = stops.First().con_name; 
     } 

預先感謝您任何幫助.... 喬

+1

謝謝亞歷山大......我現在明白你的意思是格式化。我將在未來努力,並感謝幫助。 –

回答

1

您需要使用的PropertyInfoGetValue方法:

PropertyInfo propertyInfo = 
      stops.First().GetType().GetProperty(layoutElement.field_name); 
var value = propertyInfo.GetValue(stops.First()); 
相關問題