In this article I will explain with an example, how to use
Dapper library in ASP.Net Core.
What is Dapper?
Dapper is a simple micro-ORM used to simplify working with
ADO.Net.
Dapper is an open-source object-relational mapping (ORM) library for .NET and .NET Core applications. This library allows developers quickly and easily access data from databases.
Dapper is lightweight and fast, making it an ideal choice for applications that require low latency and high performance.
It has support for both asynchronous and synchronous database queries and batching multiple queries together into a single call.
Additionally, dapper supports parameterized queries to help protect against SQL injection attacks.
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.
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.SqlClient;
Controller
The Controller consists of following Action method.
Action Method for handling GET operation
Inside this Action method, first the connection string is read from the ConnectionStrings section of the AppSettings.json file.
Then, a connection to the database is established using the SqlConnection class.
Finally, using
Query method of
Dapper library records are fetched from the
SQL Server database and returned to the View.
public class HomeController : Controller
{
public IConfiguration Configuration { get; set; }
public HomeController(IConfiguration _configuration)
{
this.Configuration = _configuration;
}
public IActionResult Index()
{
string sql = "SELECT CustomerId, Name, Country FROM Customers";
string constr = this.Configuration.GetSection("ConnectionStrings")["MyConn"];
using (SqlConnection con = new SqlConnection(constr))
{
return View(con.Query<CustomerModel>(sql));
}
}
}
View
HTML Markup
Inside the View, Generic List collection of CustomerModel class is declared as Model for the View.
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.
@using Dapper_Select_Core_MVC.Models
@modelList<CustomerModel>
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table cellpadding="0" cellspacing="0">
<tr>
<th>Customer Id</th>
<th>Name</th>
<th>Country</th>
</tr>
@foreach (CustomerModel customer in Model)
{
<tr>
<td>@customer.CustomerId</td>
<td>@customer.Name</td>
<td>@customer.Country</td>
</tr>
}
</table>
</body>
</html>
Screenshot
Downloads