2016-11-30 14 views
1

我一直在關注微軟的walkthrough on how to use Entity Framework,而是試圖把查詢的結果爲組合框,當我得到以下異常:如何將DbQuery的結果放入組合框?

「無法轉換 型「System.Data.Entity.Infrastructure的對象。 DbQuery`1 [SchoolEF.Department]'到 類型'System.Data.Entity.Core.Objects.ObjectQuery'。「

計算器上我發現this回答類似的問題搜索後,但我不知道如何使用我的計劃執行以來的情況下給出的解決方案是不是在DbQuery,我需要的DbContext到訪問數據庫。

以下是有關代碼,其中SchoolEntities擴展了DbContext,departmentList是ComboBox。

private void CourseViewer_Load(object sender, EventArgs e) 
     { 
      schoolContext = new SchoolEntities(); 

      var departmentQuery = from d in schoolContext.Departments.Include("Courses") 
            orderby d.Name 
            select d; 

      this.departmentList.DisplayMember = "Name"; 
      this.departmentList.DataSource = ((ObjectQuery)departmentQuery).Execute(MergeOption.AppendOnly); 
     } 

回答

1

這應該工作:

//... 
this.departmentList.DataSource =departmentQuery.ToList(); 

你不需要做投來設置DataSource。只需撥打ToList擴展方法即可實現查詢結果。你還應該設置ValueMember

this.departmentList.ValueMember = "Id";// PK of department entity 
0
this.departmentList.DataSource = ((ObjectQuery)departmentQuery).Execute(MergeOption.AppendOnly); 
this.departmentList.DataBind(); 

也許只是缺乏數據綁定instrction。我不知道如何將數據源放在組合框中。

相關問題