In this article I will explain with an example, how to select from
Database using
Entity Framework in C# and VB.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.
Form Design
The following form consists of:
DataGridView – For displaying data.
Configuring and connecting Entity Framework to database
Populating DataGridView using Entity Framework
Inside the
Form_Load event handler, the records are fetched from
database using
Entity Framework and assigned to the
DataSource property of the DataGridView.
C#
private void Form1_Load(object sender, EventArgs e)
{
using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
{
List<Customer> customers = (from customer in entities.Customers
select customer).ToList();
dgvCustomers.DataSource = customers;
}
}
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs)Handles MyBase.Load
Using entities As AjaxSamplesEntities = New AjaxSamplesEntities()
Dim customers As List(Of Customer) = (From customer In entities.Customers
Select customer).ToList()
dgvCustomers.DataSource = customers
End Using
End Sub
Screenshot
Downloads