In this article I will explain with an example, how to delete all records 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:
Button – For deleting all records.
Configuring and connecting Entity Framework to database
Deleting all records from Database using Entity Framework
The following event handler is executed when the Delete All Button is clicked.
Inside the event handler, the
Customer collection is passed to the
RemoveRange method of
Entity Framework and the
SaveChanges method of
Entity Framework is called which deletes the records from the database table.
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())
{
// Deleting all records from Database Table.
entities.Customers.RemoveRange(entities.Customers);
entities.SaveChanges();
MessageBox.Show("Customer records are deleted.");
}
}
VB.Net
Private Sub OnDelete(sender As Object, e As EventArgs) Handles btnDelete.Click
Using entities As AjaxSamplesEntities = New AjaxSamplesEntities()
' Deleting all records from Database Table.
entities.Customers.RemoveRange(entities.Customers)
entities.SaveChanges()
MessageBox.Show("Customer records are deleted.")
End Using
End Sub
Screenshot
Downloads