2012-07-13 56 views
0

我試圖使用實體框架加載員工。 該方法應該返回員工列表。在EF4.0的方法中返回值時拋出問題

這是給這個錯誤:

Cannot implicit convert....<Class names and methods>.... An Explicit conversion exists. 

我認爲這個問題是有關鑄造。

請檢查以下代碼。

public List<Employee> LoadEmployees() 
    { 
     try 
     { 
      EMployeeDB1Entities EE = new EMployeeDB1Entities(); 
      var Employees = EE.Employees.Where(p => p.Name.StartsWith("T")); 
      return Employees; 

     } 
     catch 
     { 
      return null; 
     } 

    } 
+0

這是編譯時或運行時錯誤嗎? – 2012-07-13 12:47:22

回答

1
var Employees = EE.Employees.Where(p => p.Name.StartsWith("T")).ToList(); 
1

更新您的代碼:

return Employees.ToList(); 

也不要注意,這是ToList()方法,實際上觸發數據庫查詢。

EE.Employees.Where(....)不查詢數據庫。當Where()的結果被枚舉爲時,查詢DB是,這是.ToList()所做的。您正在使用WPF或Silverlight


Thanks it works...one more issue, suppose if I want to bind above list to grid then how can I bind ?

假設: 要綁定在一個DataGrid您的查詢的結果,你可能暴露ObservableCollection類型的公共財產。 此集合接受一個IEnumerable<T>對象作爲構造函數。 你可以寫:

var myCollection = new ObservableCollection<Employee>(this.LoadEmployees()); 

那麼你的DataGrid的ItemSource屬性綁定到你的收藏。

如果您在使用綁定時遇到更多問題,我建議您提出另一個問題,因爲該主題相當不同。

+0

感謝它的工作原理...多一個問題,假設如果我想綁定上面的列表到網格,那我該如何綁定? – nilesh1foru 2012-07-13 13:05:24

+0

@ nilesh1foru看到更新的答案 – ken2k 2012-07-13 13:12:38