7

I've created the following Context to be used with Entity Framework Code First:

public class Context : DbContext
    {
        public DbSet<Animal> Animals { get; set; }
    }

Now I would like to use this Context in an Asp.Net application to perform CRUD operations using a GridView. I need to create a DataSource to do the data binding. How would I go about?

The ASP part would look like this:

<asp:GridView runat="server" DataSourceID="animalDataSource" DataKeyNames="AnimalID" AutoGenerateColumns="false">   
    <Columns>
        <asp:BoundField DataField="Description" HeaderText="Description" />
        <asp:CommandField ShowCancelButton="true" ShowEditButton="true" ShowDeleteButton="true" />
    </Columns>
</asp:GridView>
Myster
  • 17,704
  • 13
  • 64
  • 93
Kees C. Bakker
  • 32,294
  • 27
  • 115
  • 203
  • Related: http://stackoverflow.com/questions/6341383/how-to-create-a-nested-gridview-to-edit-ef-code-first-relation-of-ienumerablet – Kees C. Bakker Jun 14 '11 at 09:14
  • 1
    Great Q&A thanks, I retaged: -crud +objectcontext in order to try help searching. Because I didn't find this by searching for `DBContext ObjectContext GridView`. the retagging didn't help tho :-\ – Myster Nov 09 '11 at 21:36

1 Answers1

11

You can use EntityDataSource as source for your GridView and implement handler for ContextCreating event:

protected void DataSource_ContextCreating(object sender, EntityDataSourceContextCreatingEventArgs e)
{
    var context = new Context();
    e.Context = ((IObjectContextAdapter)context).ObjectContext;
}

Then you just need to configure the data source in the page. EntitySetName should be hopefully same as your DbSet property name exposed on the context.

Other way is using ObjectDataSource which will make a bridge between GridView and DbSet<Animal> but this can be more complex especially if you want bi-didrectional data binding.

Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670