Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind EF Code First DbContext to an Asp.Net DataSource?

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>
like image 491
Kees C. Bakker Avatar asked Jun 13 '11 08:06

Kees C. Bakker


People also ask

How do I use code first in an existing database?

To use code-first for an existing database, right click on your project in Visual Studio -> Add -> New Item.. Select ADO.NET Entity Data Model in the Add New Item dialog box and specify the model name (this will be a context class name) and click on Add. This will open the Entity Data Model wizard as shown below.

How do I use code first in Entity Framework?

Step 1 − First, create the console application from File → New → Project… Step 2 − Select Windows from the left pane and Console Application from the template pane. Step 3 − Enter EFCodeFirstDemo as the name and select OK. Step 4 − Right-click on your project in the solution explorer and select Manage NuGet Packages…

How do I update my Entity Framework database first?

Right-click anywhere on the design surface, and select Update Model from Database. In the Update Wizard, select the Refresh tab and then select Tables > dbo > Student. Click Finish.


1 Answers

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.

like image 182
Ladislav Mrnka Avatar answered Nov 09 '22 20:11

Ladislav Mrnka