如何将 EF Code First DbContext 绑定到 Asp.Net 数据源?
我创建了以下 Context
与 Entity Framework Code First 一起使用:
public class Context : DbContext
{
public DbSet<Animal> Animals { get; set; }
}
现在我想使用此 Context 在 Asp.Net 应用程序中使用
GridView
执行 CRUD 操作。我需要创建一个 DataSource
来进行数据绑定。我该怎么办?
ASP 部分如下所示:
<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>
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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 EntityDataSource 作为 GridView 的源并实现 ContextCreating 事件的处理程序:
然后您只需在页面中配置数据源即可。
EntitySetName
希望与上下文中公开的DbSet
属性名称相同。另一种方法是使用
ObjectDataSource
,它将在GridView
和DbSet
之间架起一座桥梁,但这可能会更复杂,特别是如果您想要双向定向数据绑定。You can use
EntityDataSource
as source for yourGridView
and implement handler forContextCreating
event:Then you just need to configure the data source in the page.
EntitySetName
should be hopefully same as yourDbSet
property name exposed on the context.Other way is using
ObjectDataSource
which will make a bridge betweenGridView
andDbSet<Animal>
but this can be more complex especially if you want bi-didrectional data binding.