Share via


Object Context Life-Cycle Management (EntityDataSource)

When using the EntityDataSource control, you can provide your own ObjectContext instance in the ContextCreating() event. The control uses this ObjectContext instance instead of creating a new one. You can also prevent the EntityDataSource control from disposing the ObjectContext in the EntityDataSourceContextDisposingEventArgs event. This is useful when you want to maintain a single ObjectContext instance in your page to be used by more than one control.

Accessing the ObjectContext

The EntityDataSourceContextCreatingEventArgs object has a Context property that can be assigned to an existing ObjectContext in the ContextCreating() event handler.

The following pattern describes how to use an ObjectContext with more than one instances of the EntityDataSource control:

  1. Instantiate the ObjectContext in the page's Load event, and assign it to a class member variable.

  2. Handle the EntityDataSourceContextCreatingEventArgs event, and assign the ObjectContext member to the Context property of the EntityDataSourceContextCreatingEventArgs object.

  3. Handle the ContextDisposing event, and set the Cancel() property of the EntityDataSourceContextDisposingEventArgs to true. This prevents the disposal of the ObjectContext.

  4. Repeat steps 2 and 3 for each EntityDataSource control in the page.

  5. Call the Dispose method to dispose the ObjectContext. The context is also disposed when the page is unloaded.

For more information on managing a long-running ObjectContext, see Managing Resources in Object Services (Entity Framework).

The following code shows how to create an ObjectContext variable for the Page object and assign it to the Context property of the EntityDataSourceContextCreatingEventArgs object.

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;
        }
    }

To keep this objCtx member for future reference, cancel the ContextCreated event as shown by the following code.

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

See Also

Concepts

EntityDataSource Events

EntityDataSource Quickstart Example

Other Resources

Data Selection using EntityDataSource

Change History

Date

History

Reason

July 2008

Added topic.

SP1 feature change.