In this article I will explain with an example, how to truncate table using
Entity Framework in ASP.Net MVC.
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.
Entity Framework Model
Once the
Entity Framework is configured and connected to the database table, the Model will look as shown below.
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, simply the View is returned.
Action method for handling POST operation
Inside the Action Method, 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.
Then, a success message is set to a
TempData object named “
Message”.
Finally, the page is redirected to Index Action method.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Truncate()
{
AjaxSamplesEntities entities = new AjaxSamplesEntities();
// Truncate Table to delete all records.
entities.Database.ExecuteSqlCommand("TRUNCATE TABLE Customers");
entities.SaveChanges();
TempData["Message"] = "Customers Table has been truncated.";
return RedirectToAction("Index");
}
}
View
HTML Markup
The View consists of HTML Form which has been created using the Html.BeginForm method with the following parameters.
asp-action – Name of the Action. In this case the name is Truncate.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The form consists of submit button.
The
TempData object named Message is checked for NULL and if it is not NULL then the value of the object is displayed using
JavaScript Alert MessageBox.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Truncate", "Home", FormMethod.Post))
{
<input type="submit" id="btnSubmit" value="Truncate" />
}
@if (TempData["Message"] != null)
{
<script type="text/javascript">
window.onload = function () {
alert('@TempData["Message"]');
};
</script>
}
</body>
</html>
Screenshot
Downloads