In this article I will explain with an example, how to truncate table 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:
Truncate – For removing all records from the table.
Configuring and connecting Entity Framework to database
Truncating Database Table using Entity Framework
The following event handler is executed when the Truncate Button is clicked.
Inside the truncate event handler, all the records are removed from the table using
ExecuteSqlCommand function of
Entity Framework which accepts the following parameters.
SQL Query - SQL Query to be executed.
Finally, a success message is displayed in MessageBox.
C#
private void OnTruncate(object sender, EventArgs e)
{
using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
{
// Truncate Table to delete all records.
entities.Database.ExecuteSqlCommand("TRUNCATE TABLE Customers");
MessageBox.Show("Customers Table has been truncated.");
}
}
VB.Net
Private Sub OnTruncate(sender As Object, e As EventArgs) Handles btnTruncate.Click
Using entities As AjaxSamplesEntities = New AjaxSamplesEntities()
' Truncate Table to delete all records.
entities.Database.ExecuteSqlCommand("TRUNCATE TABLE Customers")
MessageBox.Show("Customers Table has been truncated.")
End Using
End Sub
Screenshot
Downloads