共用方式為


物件內容生命週期管理 (EntityDataSource)

更新:2007 年 11 月

使用 EntityDataSource 控制項時,您也可以在 ContextCreating 事件中提供自己的 ObjectContext 執行個體。該控制項會使用這個 ObjectContext 執行個體,而不會建立新的。您也可以不要讓 EntityDataSource 控制項處置 EntityDataSourceContextDisposingEventArgs 事件中的 ObjectContext。當您希望頁面中的多個控制項仍然只使用單一 ObjectContext 執行個體時,這個作法相當適用。

存取 ObjectContext

EntityDataSourceContextCreatingEventArgs 物件有 Context 屬性,該屬性可以指派給 ContextCreating 事件處理常式中的現有 ObjectContext

下列規則說明如何搭配 EntityDataSource 控制項的多個執行個體使用一個 ObjectContext

  1. 在頁面的 Load 事件中產生 ObjectContext,並將其指派給類別成員變數。

  2. 處理 EntityDataSourceContextCreatingEventArgs 事件,並將 ObjectContext 成員指派給 EntityDataSourceContextCreatingEventArgs 物件的 Context 屬性。

  3. 處理 ContextDisposing 事件,並將 EntityDataSourceContextDisposingEventArgs 的 Cancel() 屬性設定為 true。如此便不會處置 ObjectContext

  4. 在頁面中對每一個 EntityDataSource 控制項,重複步驟 2 與 3。

  5. 呼叫 Dispose 方法以處置 ObjectContext。卸載頁面時會也會處置內容。

如需管理長時間執行之 ObjectContext 的詳細資訊,請參閱在物件服務中管理資源 (Entity Framework)

在下列程式碼中,示範了如何建立 Page 物件的 ObjectContext 變數,並將其指派給 EntityDataSourceContextCreatingEventArgs 物件的 Context 屬性。

public partial class _Default : System.Web.UI.Page
    {
        AdventureWorksModel.AdventureWorksEntities objCtx =
            new AdventureWorksModel.AdventureWorksEntities();

        protected void EntityDataSource2_ContextCreating(object sender, 
            EntityDataSourceContextCreatingEventArgs e)
        {
            e.Context = objCtx;
        }
    }

若要保留此 objCtx 成員以供日後參考,取消 ContextCreated 事件,如下程式碼範例所示:

        protected void EntityDataSource2_ContextDisposing(object sender, 
            EntityDataSourceContextDisposingEventArgs e)
        {
            e.Cancel = true;
        }

請參閱

概念

EntityDataSource 事件

EntityDataSource 快速入門範例

其他資源

使用 EntityDataSource 進行資料選取