In this article I will explain with an example, how to perform CRUD i.e. Create, Read, Update and Delete operations in
MySQL database with
Stored Procedure using
Dapper library in ASP.Net Core MVC.
Installing Dapper package using Nuget
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Stored Procedure
Select
DELIMITER //
CREATE PROCEDURE Customers_GetCustomers()
BEGIN
SELECT CustomerId, Name,Country
FROM Customers
END//
DELIMITER ;
Insert
This
Stored Procedure accepts
Name and
Country parameters, which are used to
Insert the records in
Customers Table.
DELIMITER //
CREATE PROCEDURE Customers_InsertCustomer(
IN Name VARCHAR(100),
IN Country VARCHAR(50)
)
BEGIN
INSERT INTO Customers(Name, Country)
VALUES(Name, Country);
SELECT LAST_INSERT_ID()
END//
DELIMITER ;
Update
This
Stored Procedure accepts
CustomerId,
Name and
Country parameters, which are used to UPDATE the records in
Customers Table.
DELIMITER //
CREATE PROCEDURE Customers_UpdateCustomer(
IN CustomerId INT,
IN Name VARCHAR(100) ,
IN Country VARCHAR(50)
)
BEGIN
UPDATE Customers
SET Name = Name,
Country = Country
WHERE Customers.CustomerId = CustomerId;
END//
DELIMITER ;
Delete
This
Stored Procedure accepts
CustomerId parameter, which is used to DELETE the records in
Customers Table.
DELIMITER //
CREATE PROCEDURE Customers_DeleteCustomer(
IN CustomerId INT
)
BEGIN
DELETE FROM Customers
WHERE Customers.CustomerId = CustomerId;
END//
DELIMITER ;
Model
The Model class consists of following properties.
public class CustomerModel
{
public int CustomerId { get; set; }
public string Name { get; set; }
public string Country { get; set; }
}
Namespaces
You will need to import the following namespaces.
using Dapper;
using System.Data;
using MySql.Data.MySqlClient;
Controllers
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, first the connection is read from the ConnectionStrings section of the AppSettings.json file.
Then, using
Query method of
Dapper library, records from the
Customers Table are fetched and stored as a Generic List collection of
CustomerModel class using
Stored Procedure.
Then, new instance of CustomerModel class is added to the list at 0th index which means the new customer will be the first element in the list.
Finally, the Generic List collection of CustomerModel class object is returned to the View.
Action method for handling Insert operation
Inside this Action method, the CustomerModel class object is received as parameter.
Then, the name of the
Stored Procedure and the
CustomerModel class object is passed to the
ExecuteScalar method of the
Dapper library which then inserts the record in the
Customers Table and inserted
CustomerId is returned back to the View as
JSON object.
Action method for handling Update operation
Inside this Action method, the CustomerModel class object is received as parameter.
Then, the name of the
Stored Procedure and the
CustomerModel class object is passed to the
Execute method of the
Dapper library which then updates the record in the
Customers Table.
Finally, the EmptyResult (NULL) is returned.
Action method for handling Delete operation
Inside this Action method, the CustomerId value is received as parameter.
Then, the name of the
Stored Procedure and the
CustomerModel class object is passed to the
Execute method of the
Dapper library which then deletes the record from the
Customers Table.
Finally, the EmptyResult (NULL) is returned.
public class HomeController : Controller
{
public IConfiguration Configuration { get; set; }
public HomeController(IConfiguration _configuration)
{
this.Configuration = _configuration;
}
public IActionResult Index()
{
string spName = "Customers_GetCustomers";
string constr = this.Configuration.GetSection("ConnectionStrings")["MyConn"];
using (MySqlConnection con = new MySqlConnection(constr))
{
List<CustomerModel> customers = con.Query<CustomerModel>(spName, commandType: CommandType.StoredProcedure).ToList();
customers.Insert(0, new CustomerModel());
return View(customers);
}
}
[HttpPost]
public IActionResult InsertCustomer(CustomerModel customer)
{
string spName = "Customers_InsertCustomer";
string constr = this.Configuration.GetSection("ConnectionStrings")["MyConn"];
using (MySqlConnection con = new MySqlConnection(constr))
{
customer.CustomerId = Convert.ToInt32(con.ExecuteScalar(spName, customer, commandType: CommandType.StoredProcedure));
return Json(customer);
}
}
[HttpPost]
public IActionResult UpdateCustomer(CustomerModel customer)
{
string spName = "Customers_UpdateCustomer";
string constr = this.Configuration.GetSection("ConnectionStrings")["MyConn"];
using (MySqlConnection con = new MySqlConnection(constr))
{
con.Execute(spName, new { customer.CustomerId, customer.Name, customer.Country }, commandType: CommandType.StoredProcedure);
}
return new EmptyResult();
}
[HttpPost]
public IActionResult DeleteCustomer(int CustomerId)
{
string spName = "Customers_DeleteCustomer";
string constr = this.Configuration.GetSection("ConnectionStrings")["MyConn"];
using (MySqlConnection con = new MySqlConnection(constr))
{
con.Execute(spName, new { CustomerId }, commandType: CommandType.StoredProcedure);
}
return new EmptyResult();
}
}
View
HTML Markup
Inside the View, in the very first line the Generic List collection of CustomerModel class is declared as Model for the View.
Display
For displaying the records, an HTML Table is used. A FOR EACH loop will be executed over the Model which will generate the HTML Table rows with the Customer records.
Insert
When the
Add Button is clicked the
Name and
Country values are fetched from their respective
TextBoxes and then passed to the
InsertCustomer Action method using
jQuery AJAX call.
Once the response is received, a new row is appended to the HTML table using the AppendRow function.
Edit
When the Edit Button is clicked, the reference of the HTML Table row is determined and the HTML SPAN elements are made hidden while the TextBoxes are made visible in the Name and Country columns of the HTML Table.
Update
When the Update Button is clicked, the reference of the HTML Table row is determined and the updated values are fetched from the respective TextBoxes of Name and Country columns and the CustomerId is determined from the HTML SPAN element of the Customer Id column.
The values of
CustomerId,
Name and
Country are passed to the
UpdateCustomer Action method using
jQuery AJAX call.
Once the response is received, the HTML SPAN elements are made visible and the TextBoxes are made hidden for the Name and Country columns of the HTML Table row.
Cancel
When the Cancel Button is clicked, the reference of the HTML Table row is determined and the HTML SPAN elements are made visible while the TextBoxes are made hidden in the Name and Country columns of the HTML Table row.
Delete
When the
Delete Button is clicked, the reference of the HTML Table row is determined and the value of the
CustomerId is fetched and passed to the
DeleteCustomer Action method using
jQuery AJAX call.
Once the response is received the respective row is removed from the HTML Table row.
@model List<CustomerModel>
@using Dapper_CRUD_SP_MySQL_Core_MVC.Models
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table id="tblCustomers" cellpadding="0" cellspacing="0">
<tr>
<th style="width:100px">Customer Id</th>
<th style="width:150px">Name</th>
<th style="width:150px">Country</th>
<th style="width:150px"></th>
</tr>
@foreach (CustomerModel customer in Model)
{
<tr>
<td class="CustomerId">
<span>@customer.CustomerId</span>
</td>
<td class="Name">
<span>@customer.Name</span>
<input type="text" value="@customer.Name" style="display:none" />
</td>
<td class="Country">
<span>@customer.Country</span>
<input type="text" value="@customer.Country" style="display:none" />
</td>
<td>
<a class="Edit" href="javascript:;">Edit</a>
<a class="Update" href="javascript:;" style="display:none">Update</a>
<a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
<a class="Delete" href="javascript:;">Delete</a>
</td>
</tr>
}
</table>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td style="width: 150px">
Name<br />
<input type="text" id="txtName" style="width:140px" />
</td>
<td style="width: 150px">
Country:<br />
<input type="text" id="txtCountry" style="width:140px" />
</td>
<td style="width: 200px">
<br />
<input type="button" id="btnAdd" value="Add" />
</td>
</tr>
</table>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
//Remove the dummy row if data present.
if ($("#tblCustomers tr").length > 2) {
$("#tblCustomers tr:eq(1)").remove();
} else {
var row = $("#tblCustomers tr:last-child");
row.find(".Edit").hide();
row.find(".Delete").hide();
row.find("span").html(' ');
}
});
//Add event handler.
$("body").on("click", "#btnAdd", function () {
var name = $("#txtName").val();
var country = $("#txtCountry").val();
$.ajax({
type: "POST",
url: "/Home/InsertCustomer",
data: { Name: name, Country: country },
success: function (r) {
var row = $("#tblCustomers tr:last-child");
if ($("#tblCustomers tr:last-child span").eq(0).html() != " ") {
row = row.clone();
}
AppendRow(row, r.CustomerId, r.Name, r.Country);
txtName.val("");
txtCountry.val("");
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
function AppendRow(row, customerId, name, country) {
//Bind CustomerId.
$(".CustomerId", row).find("span").html(customerId);
//Bind Name.
$(".Name", row).find("span").html(name);
$(".Name", row).find("input").val(name);
//Bind Country.
$(".Country", row).find("span").html(country);
$(".Country", row).find("input").val(country);
row.find(".Delete").show();
row.find(".Edit").show();
$("#tblCustomers").append(row);
};
//Edit event handler.
$("body").on("click", "#tblCustomers .Edit", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length > 0) {
$(this).find("input").show();
$(this).find("span").hide();
}
});
row.find(".Update").show();
row.find(".Cancel").show();
row.find(".Delete").hide();
$(this).hide();
});
//Update event handler.
$("body").on("click", "#tblCustomers .Update", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length > 0) {
var span = $(this).find("span");
var input = $(this).find("input");
span.html(input.val());
span.show();
input.hide();
}
});
row.find(".Edit").show();
row.find(".Delete").show();
row.find(".Cancel").hide();
$(this).hide();
var customer = {};
customer.CustomerId = row.find(".CustomerId").find("span").html();
customer.Name = row.find(".Name").find("span").html();
customer.Country = row.find(".Country").find("span").html();
$.ajax({
type: "POST",
url: "/Home/UpdateCustomer",
data: customer
});
});
//Cancel event handler.
$("body").on("click", "#tblCustomers .Cancel", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length > 0) {
var span = $(this).find("span");
var input = $(this).find("input");
input.val(span.html());
span.show();
input.hide();
}
});
row.find(".Edit").show();
row.find(".Delete").show();
row.find(".Update").hide();
$(this).hide();
});
//Delete event handler.
$("body").on("click", "#tblCustomers .Delete", function () {
if (confirm("Do you want to delete this row?")) {
var row = $(this).closest("tr");
$.ajax({
type: "POST",
url: "/Home/DeleteCustomer",
data: { CustomerId: row.find("span").html() },
success: function (response) {
if ($("#tblCustomers tr").length > 2) {
row.remove();
} else {
row.find(".Delete").hide();
row.find(".Edit").hide();
row.find("span").html(' ');
}
}
});
}
});
</script>
</body>
</html>
Screenshot
Downloads