In this article I will explain with an example, how to delete from
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.
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:
TextBox – For capturing CustomerId of the Customer record to be deleted.
Button – For deleting the record.
Configuring and connecting Entity Framework to database
Deleting records into Database using Entity Framework
The following event handler is executed when the Delete Button is clicked.
Inside the event handler, CustomerId is fetched from the TextBox.
The CustomerId value is used to reference the Customer record using
Entity Framework.
The fetched Customer object is passed to the
Remove method of
Entity Framework and the
SaveChanges method of
Entity Framework is called which updates the changes to the database.
Finally, based on whether the reference of the Customer is found or not, an appropriate message is displayed in MessageBox.
C#
private void OnDelete(object sender, EventArgs e)
{
using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
{
int customerId = int.Parse(txtId.Text);
Customer deletedCustomer = (from customer in entities.Customers
where customer.CustomerId == customerId
select customer).FirstOrDefault();
if (deletedCustomer != null)
{
entities.Customers.Remove(deletedCustomer);
entities.SaveChanges();
MessageBox.Show("Customer record deleted.");
}
else
{
MessageBox.Show("Customer not found.");
}
}
txtId.Text = string.Empty;
}
VB.Net
Private Sub OnDelete(sender As Object, e As EventArgs) Handles btnDelete.Click
Using entities As AjaxSamplesEntities = New AjaxSamplesEntities()
Dim customerId As Integer = Integer.Parse(txtId.Text)
Dim deletedCustomer As Customer = (From customer In entities.Customers
Where customer.CustomerId = customerId
Select customer).FirstOrDefault()
If deletedCustomer IsNot Nothing Then
entities.Customers.Remove(deletedCustomer)
entities.SaveChanges()
MessageBox.Show("Customer record deleted.")
Else
MessageBox.Show("Customer not found.")
End If
End Using
txtId.Text = String.Empty
End Sub
Screenshot
Downloads