In this article I will explain with an example, how to use MySqlDataReader in ASP.Net Core (.Net Core 7) Razor Pages.
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.
Namespaces
You will need to import the following namespace.
using MySql.Data.MySqlClient;
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; }
}
Razor PageModel (Code-Behind)
Inside the PageModel, a public property of Generic List collection of CustomerModel class and the IConfiguration class is created.
The IConfiguration property is set with the IConfiguration interface passed as parameter to IndexModel constructor.
The PageModel consists of following Handler method.
Handler method for handling GET operation
Inside this Handler method, the connection is read from the ConnectionStrings section of the AppSettings.json file.
Then, the records are fetched from the Customers Table using MySqlDataReader and then using WHILE loop, the records are copied into the Generic List collection of CustomerModel class objects.
public class IndexModel : PageModel
{
public IConfiguration Configuration { get; set; }
public List<CustomerModel> Customer { get; set; }
public IndexModel(IConfiguration configuration)
{
this.Configuration = configuration;
}
public void OnGet()
{
string constr = this.Configuration.GetSection("ConnectionStrings")["MyConn"];
string sql = "SELECT CustomerId, Name, Country FROM Customers";
using (MySqlConnection con = new MySqlConnection(constr))
{
using (MySqlCommand cmd = new MySqlCommand(sql, con))
{
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
this.Customer = new List<CustomerModel>();
while (sdr.Read())
{
this.Customer.Add(new CustomerModel
{
CustomerId = int.Parse(sdr["CustomerId"].ToString()),
Name = sdr["Name"].ToString(),
Country = sdr["Country"].ToString()
});
}
}
con.Close();
}
}
}
}
Razor Page (HTML)
HTML Markup
The HTML of Razor Page consists of an HTML Table for displaying the records.
Then, a FOR EACH loop will be executed over the Model property which will generate the HTML Table rows with the Customer records.
@page
@using MySqlDataReader_Core_Razor.Models
@model MySqlDataReader_Core_Razor.Pages.IndexModel
@{
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>CustomerId</th>
<th>Name</th>
<th>Country</th>
</tr>
@foreach (CustomerModel customer in Model.Customer)
{
<tr>
<td>@customer.CustomerId</td>
<td>@customer.Name</td>
<td>@customer.Country</td>
</tr>
}
</table>
</body>
</html>
Screenshot
Downloads