How to use the EntityDataSource control with the DbContext API

The EntityDataSource control is designed to work with the ObjectContext API because that’s all that existed when the control was created. The DbContext API was introduced later, in Entity Framework 4.1 alongside the Code First development workflow.  Since Code First and DbContext were introduced together you might be accustomed to associating the two, but now in Entity Framework 5.0 the DbContext API is the recommended and default API for all development workflows – Database First and Model First as well as Code First.  So if you want to use the EntityDataSource control, sooner or later you’ll want to know how to use it with the DbContext API.

Pranav Rastogi has an excellent post on this blog explaining how to do that in a Dynamic Data project (Using Dynamic Data with Entity Framework DbContext). For a regular ASP.NET Web Forms application, the workaround is different. What you have to do is handle the context creating event of the data source and provide the underlying ObjectContext instance that you get from IObjectContextAdapter. For example, here is your .aspx markup for the EntityDataSource control: 

<asp:EntityDataSource ID="SchoolContextEntityDataSource" runat="server" 
    OnContextCreating="SchoolContextEntityDataSource_ContextCreating"
    EntitySetName="Departments">
</asp:EntityDataSource>

And here is the code-behind that provides the ObjectContext:

protected void SchoolContextEntityDataSource_ContextCreating(object sender, EntityDataSourceContextCreatingEventArgs e)
{
    var db = new SchoolContext();
    e.Context = (db as IObjectContextAdapter).ObjectContext;
}

IObjectContextAdapter is in the System.Data.Entity.Infrastructure namespace:

using System.Data.Entity.Infrastructure;

Thanks to Diego Vega for showing me how to do this.

-Tom Dykstra