In this article I will explain with an example, how to delete all records 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:
Button – For deleting all records.
The Button has been assigned with an OnClick event handler.
<form id="form1" runat="server">
<asp:Button runat="server" OnClick="OnDeleteAll" Text="Delete All" />
</form>
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, Customer Collection is passed to the
RemoveRange method of
Entity Framework and the
SaveChanges method of
Entity Framework is called which updates the changes to the database.
Finally, based on whether record is deleted, an appropriate message is displayed in
JavaScript Alert Message Box using
RegisterStartupScript method.
C#
protected void OnDeleteAll(object sender, EventArgs e)
{
using (AjaxSamplesEntities entities = new AjaxSamplesEntities())
{
// Deleting all records from Database Table.
entities.Customers.RemoveRange(entities.Customers);
entities.SaveChanges();
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Customer records are deleted.');", true);
}
}
VB.Net
Private Sub OnDeleteAll(sender As Object, e As EventArgs)
Using entities As AjaxSamplesEntities = New AjaxSamplesEntities()
' Deleting all records from Database Table.
entities.Customers.RemoveRange(entities.Customers)
entities.SaveChanges()
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Customer record are deleted.');", True)
End Using
End Sub
Screenshot
Downloads