In this article I will explain with an example, how to update
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:
Label – For labelling the controls.
TextBox - For capturing the values of CustomerId, Name and Country.
Button – For updating records.
Configuring and connecting Entity Framework to database
Updating records into Database using Entity Framework
The following event handler is executed when the Update Button is clicked.
Inside the event handler, CustomerId, Name and the Country values are fetched from their respective TextBoxes.
The CustomerId value is used to reference the Customer record using
Entity Framework.
Once the record is referenced, the values of Name and Country are updated and the changes are updated into the Customers table.
Based on whether the reference of the Customer is found or not, an appropriate message is displayed in MessageBox.
C#
private void OnUpdate(object sender, EventArgs e)
{
using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
{
int customerId = int.Parse(txtId.Text);
Customer updatedCustomer = (from customer in entities.Customers
where customer.CustomerId == customerId
select customer).FirstOrDefault();
if (updatedCustomer != null)
{
updatedCustomer.Name = txtName.Text;
updatedCustomer.Country = txtCountry.Text;
entities.SaveChanges();
MessageBox.Show("Customer record updated.");
}
else
{
MessageBox.Show("Customer not found.");
}
}
txtId.Text = string.Empty;
txtName.Text = string.Empty;
txtCountry.Text = string.Empty;
}
VB.Net
Private Sub OnUpdate(sender As Object, e As EventArgs)Handles btnUpdate.Click
Using entities As AjaxSamplesEntities = New AjaxSamplesEntities()
Dim customerId As Integer = Integer.Parse(txtId.Text)
Dim updatedCustomer As Customer = (From customer In entities.Customers
Where customer.CustomerId = customerId
Select customer).FirstOrDefault()
If updatedCustomer IsNot Nothing Then
updatedCustomer.Name = txtName.Text
updatedCustomer.Country = txtCountry.Text
entities.SaveChanges()
MessageBox.Show("Customer record updated.")
Else
MessageBox.Show("Customer not found.")
End If
End Using
txtId.Text = String.Empty
txtName.Text = String.Empty
txtCountry.Text = String.Empty
End Sub
Screenshot
Downloads