In this article I will explain with an example, how to truncate table using Entity Framework in ASP.Net.
 
 

Database

I have made use of the following table Customers with the schema as follow.
Truncate Table using Entity Framework in ASP.Net
 
I have already inserted few records in the table.
Truncate Table using Entity Framework in ASP.Net
 
Note: You can download the database table SQL by clicking the download link below.
            Download SQL file
 
 

Configuring and connecting Entity Framework to database

First, you need to configure and connect Entity Framework to database.
Note: For more details on how to configure and connect Entity Framework to database, please refer my article Configure Entity Framework Step By Step in ASP.Net.
 
 

HTML Markup

The HTML Markup consists of following controls:
Truncate – For removing all records from the table.
<form id="form1" runat="server">
    <asp:Button runat="server" OnClick="OnTruncate" Text="Truncate" />
</form>
 
 

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, success message is displayed in JavaScript Alert Message Box using RegisterStartupScript method.
C#
protected void OnTruncate(object sender, EventArgs e)
{
    using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
    {
        // Truncate Table to delete all records.
        entities.Database.ExecuteSqlCommand("TRUNCATE TABLE Customers");
        ClientScript.RegisterStartupScript(this.GetType(), "alert""alert('Customers Table has been truncated.');"true);
    }
}
 
VB.Net
Protected Sub OnTruncate(sender As Object, e As EventArgs)
    Using entities As AjaxSamplesEntities = New AjaxSamplesEntities()
        ' Truncate Table to delete all records.
        entities.Database.ExecuteSqlCommand("TRUNCATE TABLE Customers")
        ClientScript.RegisterStartupScript(Me.GetType(), "alert""alert('Customers Table has been truncated.');"True)
    End Using
End Sub
 
 

Screenshot

Truncate Table using Entity Framework in ASP.Net
 
 

Downloads