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.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Configuring and connecting Entity Framework to database
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
Downloads