CRUD Operations in ASP.NET Core MVC Using ADO.NET – Step-by-Step Guide
Introduction
In this article, we will learn how to perform CRUD operations in ASP.NET Core MVC using ADO.NET and SQL Server.
CRUD stands for Create, Read, Update, and Delete. These are the four basic operations that we perform while working with a database in almost every application.
Instead of using Entity Framework Core, we will use ADO.NET to directly interact with the SQL Server database. This will help us understand how database connections, SQL commands, parameters, and data readers work internally.
For this demonstration, we will create a simple Employee Management application.
What We Will Implement
- Display all employees.
- Add a new employee.
- Edit existing employee details.
- Delete an employee.
- Implement model validation.
- Connect SQL Server using ADO.NET.
- Implement dependency injection.
Technologies Used
- ASP.NET Core MVC (.NET 8)
- C#
- ADO.NET
- Microsoft SQL Server
- Razor Views
- Bootstrap
- Visual Studio
Step 1: Create an ASP.NET Core MVC Project
Open Visual Studio and follow the steps below:
- Click on Create a new project.
- Select ASP.NET Core Web App (Model-View-Controller).
- Enter the project name as
CrudPractice. - Select .NET 8 as the framework.
- Select None as the authentication type.
- Click on Create.
Once the project is created, we will create the required Model, DAL, Controller, and Views.
Step 2: Create Database and Table
Open SQL Server Management Studio (SSMS) and execute the following SQL script.
CREATE DATABASE CrudPracticeDB;
GO
USE CrudPracticeDB;
GO
CREATE TABLE Employee
(
Id INT PRIMARY KEY IDENTITY(1,1),
Name NVARCHAR(100) NOT NULL,
Email NVARCHAR(150) NULL,
Department NVARCHAR(100) NOT NULL,
Salary DECIMAL(18,2) NULL
);Here, we have created an Employee table containing five columns.
| Column | Description |
|---|---|
| Id | Unique employee ID |
| Name | Employee name |
| Employee email address | |
| Department | Employee department |
| Salary | Employee salary |
We are using IDENTITY(1,1) to automatically generate the employee ID whenever a new record is inserted.
Let's insert some sample records.
INSERT INTO Employee
(Name, Email, Department, Salary)
VALUES
('Rahul Sharma', '[email protected]', 'IT', 35000),
('Amit Singh', '[email protected]', 'HR', 30000),
('Priya Gupta', '[email protected]', 'Finance', 40000);Step 3: Install the Required NuGet Package
To connect our ASP.NET Core application with SQL Server, we need to install the Microsoft.Data.SqlClient NuGet package.
Go to:
Tools → NuGet Package Manager → Package Manager Console
Execute the following command:
Install-Package Microsoft.Data.SqlClientThis package provides classes such as SqlConnection, SqlCommand, and SqlDataReader, which we will use to interact with SQL Server.
Step 4: Configure the Connection String
Open the appsettings.json file and add the following connection string.
{
"ConnectionStrings": {
"DefaultConnection": "Server=.;Database=CrudPracticeDB;Trusted_Connection=True;TrustServerCertificate=True;"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}Replace the server name according to your SQL Server instance.
Here:
- Server represents the SQL Server instance.
- Database represents the database name.
- Trusted_Connection enables Windows Authentication.
- TrustServerCertificate allows us to use an untrusted server certificate for local development.
For production applications, use a trusted SQL Server certificate instead of bypassing certificate validation.
Step 5: Create the Employee Model
Inside the Models folder, create a class named Employee.cs.
using System.ComponentModel.DataAnnotations;
namespace CrudPractice.Models
{
public class Employee
{
public int Id { get; set; }
[Required(ErrorMessage = "Name is required")]
[StringLength(100)]
public string? Name { get; set; }
[EmailAddress(ErrorMessage = "Invalid email address")]
[StringLength(150)]
public string? Email { get; set; }
[Required(ErrorMessage = "Department is required")]
[StringLength(100)]
public string? Department { get; set; }
[Range(typeof(decimal), "0", "9999999999999999.99",
ErrorMessage = "Enter a valid non-negative salary")]
public decimal? Salary { get; set; }
}
}Understanding the Model
The Employee model represents the structure of our Employee table.
We are also using Data Annotations to validate employee information before saving it into the database.
- Required: Ensures that the field is not empty.
- EmailAddress: Validates the email format if an email is entered.
- StringLength: Restricts the maximum length of a string.
- Range: Ensures that the salary is within the allowed range if entered.
In this example, Email and Salary are optional fields.
Step 6: Create the Data Access Layer (DAL)
Create a new folder named DAL inside the project.
Inside this folder, create a class named EmployeeDAL.cs.
The main purpose of creating a separate Data Access Layer is to keep all database-related operations in one place instead of writing SQL queries directly inside the Controller.
EmployeeDAL.cs
using CrudPractice.Models;
using Microsoft.Data.SqlClient;
using System.Data;
namespace CrudPractice.DAL
{
public class EmployeeDAL
{
private readonly string _configuration;
public EmployeeDAL(IConfiguration configuration)
{
_configuration = configuration
.GetConnectionString("DefaultConnection")
?? throw new InvalidOperationException(
"Connection string not found");
}
public List<Employee> GetAllEmployee()
{
List<Employee> employee = new List<Employee>();
using (SqlConnection con =
new SqlConnection(_configuration))
{
string query = "SELECT * FROM Employee";
using SqlCommand cmd =
new SqlCommand(query, con);
con.Open();
using SqlDataReader reader =
cmd.ExecuteReader();
while (reader.Read())
{
Employee emp = new Employee();
emp.Id = Convert.ToInt32(reader["Id"]);
emp.Name = reader["Name"].ToString();
emp.Email = reader["Email"] == DBNull.Value
? null
: reader["Email"].ToString();
emp.Department =
reader["Department"].ToString();
emp.Salary = reader["Salary"] == DBNull.Value
? null
: Convert.ToDecimal(reader["Salary"]);
employee.Add(emp);
}
}
return employee;
}
public void AddEmployee(Employee emp)
{
using (SqlConnection con =
new SqlConnection(_configuration))
{
string query = @"INSERT INTO Employee
(Name, Email, Department, Salary)
VALUES
(@Name, @Email, @Department, @Salary)";
using SqlCommand cmd =
new SqlCommand(query, con);
AddEmployeeParameters(cmd, emp);
con.Open();
cmd.ExecuteNonQuery();
}
}
public Employee? GetEmployeeById(int id)
{
Employee? emp = null;
using (SqlConnection con =
new SqlConnection(_configuration))
{
string query =
"SELECT * FROM Employee WHERE Id = @Id";
using SqlCommand cmd =
new SqlCommand(query, con);
cmd.Parameters.Add("@Id", SqlDbType.Int)
.Value = id;
con.Open();
using SqlDataReader reader =
cmd.ExecuteReader();
if (reader.Read())
{
emp = new Employee();
emp.Id = Convert.ToInt32(reader["Id"]);
emp.Name = reader["Name"].ToString();
emp.Email = reader["Email"] == DBNull.Value
? null
: reader["Email"].ToString();
emp.Department =
reader["Department"].ToString();
emp.Salary = reader["Salary"] == DBNull.Value
? null
: Convert.ToDecimal(reader["Salary"]);
}
}
return emp;
}
public void UpdateEmployee(Employee emp)
{
using (SqlConnection con =
new SqlConnection(_configuration))
{
string query = @"UPDATE Employee SET
Name = @Name,
Email = @Email,
Department = @Department,
Salary = @Salary
WHERE Id = @Id";
using SqlCommand cmd =
new SqlCommand(query, con);
cmd.Parameters.Add("@Id", SqlDbType.Int)
.Value = emp.Id;
AddEmployeeParameters(cmd, emp);
con.Open();
cmd.ExecuteNonQuery();
}
}
public void DeleteEmployee(int id)
{
using (SqlConnection con =
new SqlConnection(_configuration))
{
string query =
"DELETE FROM Employee WHERE Id = @Id";
using SqlCommand cmd =
new SqlCommand(query, con);
cmd.Parameters.Add("@Id", SqlDbType.Int)
.Value = id;
con.Open();
cmd.ExecuteNonQuery();
}
}
private void AddEmployeeParameters(
SqlCommand cmd, Employee emp)
{
cmd.Parameters.Add("@Name", SqlDbType.NVarChar, 100)
.Value = (object?)emp.Name ?? DBNull.Value;
cmd.Parameters.Add("@Email", SqlDbType.NVarChar, 150)
.Value = (object?)emp.Email ?? DBNull.Value;
cmd.Parameters.Add("@Department",
SqlDbType.NVarChar, 100)
.Value = (object?)emp.Department ?? DBNull.Value;
SqlParameter salary =
cmd.Parameters.Add("@Salary", SqlDbType.Decimal);
salary.Precision = 18;
salary.Scale = 2;
salary.Value = (object?)emp.Salary ?? DBNull.Value;
}
}
}Understanding the ADO.NET Components
Before moving to the Controller, let's understand the important ADO.NET components used in the above code.
| Component | Purpose |
|---|---|
| SqlConnection | Establishes a connection with SQL Server |
| SqlCommand | Executes SQL queries or stored procedures |
| SqlDataReader | Reads records returned by a query |
| ExecuteReader() | Returns records from a database |
| ExecuteNonQuery() | Executes INSERT, UPDATE, and DELETE operations |
| SqlParameter | Passes values securely to SQL queries |
| IConfiguration | Reads the connection string from appsettings.json |
| DBNull.Value | Represents a SQL NULL value |
Why Are We Using the Using Statement?
The using statement automatically disposes of the database connection and other disposable resources once their work is completed, even if an exception occurs.
This helps us manage database resources properly.
Why Are We Using Parameterized Queries?
Instead of directly concatenating user input into SQL queries, we are passing values through SQL parameters.
For example:
Join the conversation! Your thoughts help the community grow.