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

纵然是瞬间 提交于 2019-11-29 09:36:49

问题


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>

回答1:


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.



来源:https://stackoverflow.com/questions/6327937/how-to-bind-ef-code-first-dbcontext-to-an-asp-net-datasource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!