In this article I will explain with an example, how to insert into
Database using
Entity Framework with C# and VB.Net in Windows Forms (WinForms) Application.
Database
I have made use of the following table Customers with the schema as follow.
Note: You can download the database table SQL by clicking the download link below.
Form Design
The following Form consists of:
Label – For labelling the controls.
TextBox – For capturing Name to be inserted.
ComboBox – For selecting Country name to be inserted.
Configuring and connecting Entity Framework to database
Inserting records into Database using Entity Framework
The following event handler is executed when the Insert Button is clicked.
Inside the event handler, name and the country values are fetched from their respective Controls and then passed through an object of Customer class to the
Add method of Customers properties using
Entity Framework.
Finally, the SaveChanges method of
Entity Framework is called which Inserts the Customer to the database and inserted CustomerId is fetched and displayed in
MessageBox.
C#
private void Form1_Load(object sender, EventArgs e)
{
cbCountries.Items.Add("United States");
cbCountries.Items.Add("India");
cbCountries.Items.Add("France");
cbCountries.Items.Add("Russia");
}
private void OnInsert(object sender, EventArgs e)
{
int customerId;
using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
{
Customer customer = new Customer
{
Name = txtName.Text,
Country = cbCountries.SelectedItem.ToString()
};
entities.Customers.Add(customer);
entities.SaveChanges();
customerId = customer.CustomerId;
}
txtName.Text = string.Empty;
cbCountries.Text = string.Empty;
MessageBox.Show("Inserted Customer ID: " + customerId);
}
VB.Net
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cbCountries.Items.Add("United States")
cbCountries.Items.Add("India")
cbCountries.Items.Add("France")
cbCountries.Items.Add("Russia")
End Sub
Private Sub OnInsert(sender As Object, e As EventArgs) Handles btnInsert.Click
Dim customerId As Integer
Using entities As AjaxSamplesEntities = New AjaxSamplesEntities()
Dim customer As Customer = New Customer With {
.Name = txtName.Text,
.Country = cbCountries.SelectedItem.ToString()
}
entities.Customers.Add(customer)
entities.SaveChanges()
customerId = customer.CustomerId
End Using
txtName.Text = String.Empty
cbCountries.Text = String.Empty
MessageBox.Show("Inserted Customer ID: " & customerId)
End Sub
Screenshot
Record after Insert in Database
Downloads