| Lesson 4 | Deleting Records |
| Objective | Use the recordset object to delete records. |
Deleting Database Records
The VirtualBookShelf application needs the ability to remove records, not just add and change them. Books fall out of print and stop being carried, and customers who haven't ordered in years don't need to stay in the database forever. This lesson builds the third and final handler this module set out to create: a Delete button, and it turns out to be the simplest of the three.
The legacy version of this lesson needed exactly one line of script, a call to the Recordset's deleteRecord method, less than either the Update or Insert buttons required. The modern version follows the same pattern: a DELETE statement is the shortest kind of SQL this module has written, and the handler built around it is correspondingly short too.
What the Legacy Simulation Did
The walkthrough picked up in the same file as the previous two lessons,
CustManage_1.asp, adding a Button DTC just below the Insert button already there. Naming it
DeleteBtn, captioning it
Delete, and opening the Script Outline to its
onclick event left one line to add:
Sub DeleteBtn_onclick
CustRecords.deleteRecord
End Sub
That's the entire implementation, no field assignments, no separate commit step. Clicking Delete removed the currently displayed customer immediately, and the next record in the Recordset appeared in its place. Compared to the Update button's parameterized field assignments and the Insert button's two-call
addRecord/
updateRecord sequence, this was the shortest of the three by a wide margin, and that pattern carries straight through to the modern version.
Testing the Delete Before It's Wrapped in a Handler
Every SQL statement this module has written started in Azure Data Studio first, and a DELETE statement deserves that habit more than most, since there's no undo once it commits. Running DELETE FROM Customer WHERE CustomerID = 999; directly against a test row confirms the statement targets exactly the row intended, and running SELECT * FROM Customer WHERE CustomerID = 999; immediately afterward confirms it's actually gone. That two-statement check costs a few seconds and catches a WHERE clause mistake, say, one left out entirely, which would delete every row in the table, before it ever runs from inside an application.
The Simplest Statement in This Module: DELETE
An
UPDATE statement needs a
SET clause naming every column being changed. An
INSERT statement needs a full column list and a matching list of values. A
DELETE statement needs neither:
DELETE FROM Customer WHERE CustomerID = @CustomerID;
There's nothing to set and nothing to insert, just a row to identify and remove. That's the direct modern equivalent of
CustRecords.deleteRecord's own one-line simplicity: where the legacy method call hid its work behind a single statement, the modern
SqlCommand is just as short, because the SQL itself genuinely is this simple.
Building the Delete Handler
Here's the complete implementation, filling in the last of the three comments this module's first lesson left behind:
public async Task<IActionResult> OnPostDeleteAsync(int customerId)
{
using SqlConnection connection = new(_connectionString);
await connection.OpenAsync();
SqlCommand command = new(
"DELETE FROM Customer WHERE CustomerID = @CustomerID",
connection);
command.Parameters.AddWithValue("@CustomerID", customerId);
int rowsAffected = await command.ExecuteNonQueryAsync();
if (rowsAffected == 0)
{
ModelState.AddModelError(string.Empty,
"That customer record could not be found. It may have already been deleted.");
return Page();
}
return RedirectToPage("./Index");
}
This follows the exact pattern Lesson 2 established for
OnPostUpdateAsync: open a connection, build a parameterized command, run it, and check
rowsAffected before deciding what happened. A delete that matches zero rows isn't an error from SQL Server's point of view, the statement ran perfectly fine, it just didn't find the row a visitor was expecting to remove, most likely because someone else already deleted it. Checking the row count is the only way to notice that and tell the visitor something useful instead of silently redirecting as if the delete had succeeded.
Wiring the Form to the Handler
The Deleted-Row Cursor Trap That Doesn't Exist Here
Classic ADO's Recordset.Delete had a sharp edge the legacy simulation's own button never had to show a visitor, but a developer writing the script underneath it did. Calling rs.Delete removed the row from the database immediately, but the cursor stayed positioned on that now-deleted row until something moved it. Reading any field from the Recordset in that in-between state, before calling rs.MoveNext or rs.MovePrevious, raised a runtime error: the row the cursor was pointing at simply didn't exist anymore.
ADO.NET has nothing resembling this, and not because it solved the problem, but because it never created it. A SqlCommand running a DELETE statement doesn't leave any cursor positioned anywhere afterward; there's no Recordset, no current row, no state to manage once ExecuteNonQueryAsync returns. The statement either removed a row or it didn't, and the integer it returns is the only thing left to check.
Wrapping the Handler in Structured Error Handling
VirtualBookShelf's current schema, just
Customer and
Inventory, has no table that references a
Customer row by foreign key, so nothing stops this handler's
DELETE statement from succeeding today. That won't necessarily stay true forever; a future order-history table, for instance, might reference
CustomerID directly, and deleting a customer who still has related rows would then fail with SQL Server's familiar error 547. Writing the handler to expect that possibility now costs nothing and saves a rewrite later:
public async Task<IActionResult> OnPostDeleteAsync(int customerId)
{
try
{
using SqlConnection connection = new(_connectionString);
await connection.OpenAsync();
SqlCommand command = new(
"DELETE FROM Customer WHERE CustomerID = @CustomerID",
connection);
command.Parameters.AddWithValue("@CustomerID", customerId);
int rowsAffected = await command.ExecuteNonQueryAsync();
if (rowsAffected == 0)
{
ModelState.AddModelError(string.Empty, "That customer record could not be found.");
return Page();
}
return RedirectToPage("./Index");
}
catch (SqlException ex) when (ex.Number == 547)
{
ModelState.AddModelError(string.Empty,
"This customer can't be deleted because related records still reference it.");
return Page();
}
catch (SqlException ex)
{
_logger.LogError(ex, "Failed to delete CustomerID {CustomerId}", customerId);
ModelState.AddModelError(string.Empty, "Something went wrong deleting that record. Please try again.");
return Page();
}
}
Nothing about this structure is new; it's the same ordered catch pattern, specific error first, general
SqlException second, that Lesson 3 used for a duplicate email and Module 4's error-handling lesson introduced in the first place.
An Alternative Worth Knowing: Soft Deletes
Physically removing a row, what this lesson's handler does, isn't the only way to handle a customer who hasn't ordered in years. A common alternative is a soft delete: adding a column such as
IsActive or
DeletedDate to
Customer, and replacing the
DELETE statement with an
UPDATE that simply marks a row as inactive instead of removing it.
UPDATE Customer SET IsActive = 0 WHERE CustomerID = @CustomerID;
A soft delete keeps the row's history intact, useful if anything elsewhere in the database ever needs to reference that customer again, and it's trivially reversible: restoring a mistakenly deleted customer is another
UPDATE rather than a restore from backup. The cost is that every query elsewhere in the application now needs to filter out inactive rows, typically with a
WHERE IsActive = 1 added everywhere
Customer is read. VirtualBookShelf's schema doesn't currently have an
IsActive column, so this lesson's handler performs a genuine, permanent delete, but it's worth knowing the alternative exists for a column that might get added later.
Looking Back at All Three Operations
With this lesson's handler finished, it's worth seeing this module's three statements side by side, since the differences between them are exactly what made each lesson's own complexity level what it was:
-- Lesson 2: UPDATE needs a SET clause and a WHERE clause
UPDATE Customer SET Email = @NewEmail WHERE CustomerID = @CustomerID;
-- Lesson 3: INSERT needs a column list and a matching VALUES list
INSERT INTO Customer (FirstName, LastName, Email, Phone)
OUTPUT INSERTED.CustomerID
VALUES (@FirstName, @LastName, @Email, @Phone);
-- Lesson 4: DELETE needs only a WHERE clause
DELETE FROM Customer WHERE CustomerID = @CustomerID;
Each one is exactly as long as it needs to be and no longer.
UPDATE sits in the middle, naming the columns changing but not every column on the table.
INSERT is the longest, because a brand new row has no existing values to fall back on, every column that matters has to be named explicitly.
DELETE is the shortest, because removing a row needs no column information at all, only enough to identify which row to remove. The C# handler wrapped around each one followed the same shape every time: open a connection, build a parameterized command, run it with the method suited to what it returns, and check the result before deciding what to tell the visitor.
Frequently Asked Questions
Why does this handler check rowsAffected when a DELETE statement either succeeds or fails? Because matching zero rows and matching one row are both forms of success from SQL Server's perspective, the statement itself never errors in either case. Only the row count tells the handler which one actually happened, the same distinction Lesson 2's Update handler needed.
Could this handler delete more than one row at a time? With a different WHERE clause, yes; DELETE FROM Customer WHERE DateJoined < @CutoffDate would remove every customer who joined before a given date, all in one statement. Classic ADO needed a separate mechanism for this, setting a Recordset's Filter property and calling rs.Delete adAffectGroup followed by rs.UpdateBatch. A parameterized DELETE ... WHERE statement does the same job in SQL directly, with no separate batch step required.
What was the Unique Table property for in classic ADO? It solved a problem specific to a Recordset opened over a JOIN between two tables: without it, calling rs.Delete could attempt to delete from both base tables at once. Setting Unique Table told the provider which single table to actually delete from. This module's Delete handler works against one table directly, so the problem that property solved never comes up here.
Is EF Core's ExecuteDeleteAsync() method worth knowing about, even though this module didn't use it? Yes, it's real, current functionality, a direct bulk delete that skips loading an entity into memory first. It's still built on top of EF Core, though, which this course continues to defer; this module's handler reaches the same result with a parameterized SqlCommand instead.
Does Optimized Locking change anything about how this Delete handler behaves? Not from the handler's point of view. Optimized Locking, TID labeling and Lock-After-Qualification under RCSI, affects how SQL Server manages locks internally while a statement runs, but a parameterized DELETE statement looks and behaves identically to the handler whether that feature is active or not.
Why include a confirmation step and a Cancel link if neither is required? Because a Delete button that acts immediately on click, with no way to back out, is unforgiving of an accidental click in a way an Update or Insert button isn't; both of those can simply be edited again. A confirmation page is a small amount of extra friction that meaningfully protects against an action with no undo.
What should happen if a visitor submits the Delete form twice, say by clicking the button twice quickly? The second request's DELETE statement matches zero rows, since the first request already removed it, and the row-count check catches that cleanly: the visitor sees "record could not be found" rather than an error, which is an accurate description of what actually happened.
Could the error 547 catch block ever actually run against VirtualBookShelf's current schema? Not yet. Neither Customer nor Inventory currently has a foreign key referencing the other, so nothing in this course's schema as it stands today would trigger it. It's included anyway because it costs nothing to write and because a schema can grow a foreign key relationship later without this handler needing to change at all.
What is ON DELETE CASCADE, and would it change how this handler works? It's an option set on a foreign key constraint itself, telling SQL Server to automatically delete related child rows whenever a parent row is deleted, rather than blocking the delete with error 547. If a future order-history table's foreign key back to Customer were created with ON DELETE CASCADE, this handler's DELETE statement would succeed and quietly remove the related orders too; without it, the same delete would fail with error 547 instead. Which behavior is correct depends entirely on whether losing that related history along with the customer is actually the intended outcome, a schema design decision rather than something this handler's code controls.
Why does a soft delete need every other query to add a filter, when a hard delete doesn't? Because after a hard delete, the row is simply gone, so there's nothing left to accidentally include. After a soft delete, the row is still physically present in the table, just flagged, so any query that doesn't explicitly exclude inactive rows will include them by default, exactly the opposite of what's usually wanted.
What's Ahead
With this lesson's Delete handler complete, this module's three stated objectives, an Update button, an Insert button, and a Delete button, are all built, each one the same way: a parameterized SqlCommand, a check on what ExecuteNonQueryAsync or ExecuteScalarAsync actually returned, and structured error handling around the parts that can fail. Every one of them replaced a piece of classic ADO's Recordset object, updateRecord, the two-call addRecord/updateRecord sequence, and now deleteRecord, with a single, direct SQL statement.
The next lesson moves to a different kind of problem: coercing scripting data types to match the types a database column actually expects, the same concern that quietly sat underneath every parameter this module has built so far, now addressed directly.
