In this article I will explain with an example, how to select from
Database using
Entity Framework in ASP.Net.
Database
I have made use of the following table Customers with the schema as follow.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Configuring and connecting Entity Framework to database
HTML Markup
The HTML Markup consists of following Controls:
GridView – For displaying data.
The GridView consists of three BoundField columns.
<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="CustomerId" HeaderText="CustomerId" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Country" HeaderText="Country" />
</Columns>
</asp:GridView>
Populating GridView using Entity Framework
Inside the
Page_Load event handler, the records are fetched from
database using
Entity Framework and assigned to the
DataSource property of the GridView and
DataBind is called.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
{
List<Customer> customers = (from customer in entities.Customers
select customer).ToList();
gvCustomers.DataSource = customers;
gvCustomers.DataBind();
}
}
}
VB.Net
Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Using entities As AjaxSamplesEntities = New AjaxSamplesEntities()
Dim customers As List(Of Customer) = (From customer In entities.Customers
Select customer).ToList()
gvCustomers.DataSource = customers
gvCustomers.DataBind()
End Using
End Sub
Screenshot
Downloads