In this article I will explain a simple tutorial with an example, how to use simple
Entity Framework in ASP.Net Web Forms with C# and VB.Net.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Configuring and connecting Entity Framework to database
1. Inside the Solution Explorer, right click on Project and then click on Add and then click on Add New Item.
2. Then, inside the Add New Item window, select ADO.NET Entity Data Model option.
3. As soon as you add the Entity Data Model to your project you will be prompted with the following dialog and you need to click YES button.
4. Then, the Entity Data Model Wizard will open up where you need to select EF Designer from database.
5. After that, click on New Connection Button.
6. Now the wizard will ask you to connect and configure the connection string to the database.
After connecting to the database, click on Test Connection and if connection was successful it will display the Success message.
7. Then, click on Next Button to move on to the Next step.
8. Now, you need to select the Table you need to connect and work with Entity Framework and click on Finish Button.
Finally, the Entity Data Model ready with the Customers Table of the Northwind database.
HTML Markup
The HTML Markup consists of following control:
GridView – For displaying data.
<h4>Customers</h4>
<hr />
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="Customer Id" />
<asp:BoundField DataField="ContactName" HeaderText="ContactName" />
<asp:BoundField DataField="City" HeaderText="City" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
Binding GridView with Entity Framework using C# and VB.Net
Inside the
Page Load event handler, the Top 10 records from the
Customers table are fetched using
Entity Framework
and assigned to the DataSource property of the GridView control.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
using (NORTHWINDEntities entities = new NORTHWINDEntities())
{
gvCustomers.DataSource = (from customer in entities.Customers.Take(10)
select customer).ToList();
gvCustomers.DataBind();
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBackThen
Using entities As NORTHWINDEntities = New NORTHWINDEntities()
gvCustomers.DataSource = (From customer In entities.Customers.Take(10) Select customer).ToList()
gvCustomers.DataBind()
End Using
End If
End Sub
Screenshot
Downloads