2012-11-19 44 views
0

我想從實體框架對象中的多個屬性獲取值。有11個屬性,每個屬性分配一個日期。我已經使用反射嘗試,但我不斷收到一個錯誤「對象不匹配目標類型」對象不匹配循環通過EF屬性的目標類型

public void CheckWeekStatus() 
    { 
    var currentFlexi = from c in FlexiContext.FlexPeriods where c.FlexiCurrentYear == true select c; 

    FlexPeriod s = new FlexPeriod(); 

    PropertyInfo[] properties = s.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); 

     foreach (var info in properties) 
      {      
      var o = info.GetValue(currentFlexi,null);           
      } 
    } 

FlexPeriod是包含所有屬性的類型。我可以遍歷屬性,但很顯然,我正在嘗試訪問值的方式做錯了什麼。任何建議,將不勝感激。

回答

5

首先,你可以得到Type沒有實例化對象:

PropertyInfo[] properties = typeof(FlexPeriod).GetProperties(... 

原因GetValue失敗是currentFlexiFlexPeriod對象(實際上是一個IEnumerable<FlexPeriod>)的集合,而不是一個單一實例的FlexPeriod

+0

我認爲這是說。 –

+0

非常感謝,它現在正在工作。 – mjroodt

+0

不客氣:) –

相關問題