2011-11-06 37 views
2

我是相當新的實體框架和LINQ。我之前使用過DataGridView並設置了它的數據源的DataBind()在C#

DataGridView1.datasource=dt; // dt=datatable 

就夠了。但是在讀ASP.Net的書,他們已經給出了使用實體框架的代碼

using (PlanetWroxEntities myEntities = new PlanetWroxEntities()) 
{ 
    var allGenres = from genre in myEntities.Genres 
    orderby genre.Name 
    select new { genre.Name, genre.Reviews }; 
    GridView1.DataSource = allGenres; 
    GridView1.DataBind(); 
} 

這是爲什麼DataBind()在末尾。我見過的MSDN文檔DataBind()它說「(這)將數據源綁定到調用的服務器控件及其所有子控件。」

如果我刪除它,我得到一個錯誤,因爲「該ObjectContext實例已被處置,不能再用於需要連接的操作。」

所以我只是困惑的是,這是什麼DataBind()實際上呢?我看到一些人也使用DataBind for DataGridView,我不知道爲什麼?

謝謝。

回答

1

DataBind方法迫使被讀取並結合到控制數據源。既然你你處置事後PlanetWroxEntities範圍內進行數據綁定,控制應在PlanetWroxEntities處置前,讀取來自數據源的數據。換句話說:在數據庫連接關閉之前。

另一種方法是通過調用.ToList()方法強制查詢。這將DataSource屬性設置爲包含具體數據的非惰性列表。

using (PlanetWroxEntities myEntities = new PlanetWroxEntities()) 
{ 
    var allGenres = from genre in myEntities.Genres 
    orderby genre.Name 
    select new { genre.Name, genre.Reviews }; 
    GridView1.DataSource = allGenres.ToList(); 
}