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.
Select from Database using Entity Framework in ASP.Net
 
I have already inserted few records in the table.
Select from Database using Entity Framework in ASP.Net
 
Note: You can download the database table SQL by clicking the download link below.
            Download SQL file
 
 

Configuring and connecting Entity Framework to database

First, you need to configure and connect Entity Framework to database.
Note: For more details on how to configure and connect Entity Framework to database, please refer my article Configure Entity Framework Step By Step in ASP.Net.
 
 

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

Select from Database using Entity Framework in ASP.Net
 
 

Downloads