In this article I will explain with an example, how to use
ADO.Net in ASP Net Core (.Net Core 6) MVC.
Installing System.Data.SqlClient package
By default like ASP.Net, ASP.Net MVC and .Net Core 3.0, System.Data.SqlClient package is not available in ASP Net Core (.Net Core 6) MVC.
Thus, in order to use
System.Data.SqlClient package, you need to install the
System.Data.SqlClient package from
Nuget using
Package Manager Console.
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 namespaces.
using System.Data;
using System.Data.SqlClient;
Controller
The Controller consists of the following Action methods.
Action method for handling GET operation
Inside this Action method, the records are fetched from the
Customers Table using
ADO.Net.
Then, the records are inserted into a DataSet using Fill method of the SqlDataAdapter class object.
Finally, the DataSet is returned to the View.
public class HomeController : Controller
{
public IActionResult Index()
{
string constr = @"Data Source=.\SQL2019;Initial Catalog=AjaxSamples;integrated security=true";
string sql = "SELECT CustomerId, Name, Country FROM Customers";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlDataAdapter sda = new SqlDataAdapter(sql, con))
{
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return View(ds);
}
}
}
}
}
View
HTML Markup
Inside the View, the System.Data namespace is inherited.
For displaying the records, an HTML Table is used. A FOR EACH loop will be executed over the rows of the
DataTable which will generate the HTML Table rows with the Customer records.
@using System.Data;
@{
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 (DataRow row in Model.Tables[0].Rows)
{
<tr>
<td>@row["CustomerId"]</td>
<td>@row["Name"]</td>
<td>@row["Country"]</td>
</tr>
}
</table>
</body>
</html>
Screenshot
Downloads