如何EF code首先的DbContext绑定到一个Asp.Net数据源? [英] How to bind EF Code First DbContext to an Asp.Net DataSource?

查看:172
本文介绍了如何EF code首先的DbContext绑定到一个Asp.Net数据源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下上下文将与使用实体框架的 code首先

 公共类语境的DbContext
    {
        公共DbSet<动物>动物{搞定;组; }
    }

现在我想用这个上下文在Asp.Net应用程序执行的 CRUD 使用 GridView控件操作。我需要创建一个数据源做数据绑定。我怎么会去?

在ASP部分是这样的:

 < ASP:GridView控件=服务器的DataSourceID =animalDataSource的DataKeyNames =AnimalID的AutoGenerateColumns =false的>
    <柱体和GT;
        < ASP:BoundField的数据字段=说明的HeaderText =说明/>
        < ASP:CommandField中ShowCancelButton =真ShowEditButton =真的ShowDeleteButton =真/>
    < /专栏>
< / ASP:GridView的>


解决方案

您可以使用 EntityDataSource 源为你的 GridView控件和实施处理程序 ContextCreating 事件:

 保护无效DataSource_ContextCreating(对象发件人,EntityDataSourceContextCreatingEventArgs E)
{
    VAR语境=新的上下文();
    e.Context =((IObjectContextAdapter)上下文).ObjectContext;
}

然后你只需要配置在页面中的数据源。 EntitySetName 应尽可能暴露在上下文中的 DbSet 属性名相同的希望。

另一种方法是使用 ObjectDataSource控件这将使 GridView控件 DbSet℃之间的桥梁;动物方式> 但是这样做的,特别是如果你想双didrectional数据绑定更复杂的

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>

解决方案

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.

这篇关于如何EF code首先的DbContext绑定到一个Asp.Net数据源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆