In this article I will explain with an example, how to implement Entity Framework Database First Approach in Windows Forms (WinForms) Application using C# and VB.Net.
This article will illustrate how to use Entity Framework Database First Approach to populate DataGridView in Windows Forms (WinForms) Application using 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 in Windows Forms Application
Now I will explain the steps to configure and add Entity Framework and also how to connect it with the database in Windows Forms application.
You will need to add Entity Data Model to your project by right clicking the Solution Explorer and then click on Add and then New Item option of the Context Menu.
From the Add New Item window, select ADO.NET Entity Data Model and set its Name as NorthwindModel and then click Add.
Then the Entity Data Model Wizard will open up where you need to select EF Designer database option.
Now the wizard will ask you to connect and configure the Connection String to the database.
You will need to select the
1. SQL Server Instance.
2. Database.
And then click Test Connection to make sure all settings are correct.
Once the Connection String is generated, click Next button to move to the next step.
Next you will need to choose the Entity Framework version to be used for connection.
Now you will need to choose the Tables, you need to connect and work with Entity Framework. Here Customers Table needs to be selected.
The above was the last step and you should now have the Entity Data Model ready with the Customers Table of the Northwind Database
Form Design
The below Form consists of a DataGridView control.
Populating DataGridView using Entity Framework Database First Approach
Inside the Form Load event, the records from the Customers Table are fetched using Entity Framework and are assigned to the DataSource property of the DataGridView control.
C#
private void Form1_Load(object sender, EventArgs e)
{
NorthwindEntities entities = new NorthwindEntities();
var customers = from p in entities.Customers
select new
{
CustomerId = p.CustomerID,
ContactName = p.ContactName,
Country = p.Country
};
dataGridView1.DataSource = customers.ToList();
}
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim entities As NorthwindEntities = New NorthwindEntities()
Dim customers = From p In entities.Customers _
Select New With {.CustomerId = p.CustomerID, _
.ContactName = p.ContactName, _
.Country = p.Country}
dataGridView1.DataSource = customers.ToList()
End Sub
Screenshot
Downloads