# Add Soft Delete to an ASP.NET Core App

Yes. An agent adds soft delete to your ASP.NET Core Clean Architecture app with an EF Core interceptor, query filters, restore commands and NUnit tests, in a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-soft-delete/aspnet-core/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads the data layer first. In a solution shaped like jasontaylordev/CleanArchitecture, global.json pins the .NET SDK 10.0.402 and Directory.Packages.props manages versions centrally: Microsoft.EntityFrameworkCore 10.0.13, MediatR 14.2.0, FluentValidation 12.2.0, AutoMapper 16.2.0, Ardalis.GuardClauses 5.0.0, and for tests NUnit 5.0.0, Shouldly 4.3.0, Respawn 7.0.0 and Aspire.Hosting.Testing 13.6.2. src/Domain/Common/BaseEntity.cs holds an int Id and the domain events list; BaseAuditableEntity.cs adds Created, CreatedBy, LastModified and LastModifiedBy; TodoList and TodoItem extend it. src/Infrastructure/Data/Interceptors/AuditableEntityInterceptor.cs is a SaveChangesInterceptor that stamps those fields from `IUser` and `TimeProvider` on Added and Modified entries, registered in Infrastructure/DependencyInjection.cs as an `ISaveChangesInterceptor` beside DispatchDomainEventsInterceptor and handed to `AddDbContext` through `options.AddInterceptors`. ApplicationDbContext.cs extends IdentityDbContext and applies every IEntityTypeConfiguration in the assembly; TodoListConfiguration.cs sets a 200-character title and owns the Colour value object. ApplicationDbContextInitialiser.cs calls EnsureDeletedAsync then EnsureCreatedAsync, so there is no Migrations folder to extend.

It then reads how deletes happen. DeleteTodoItemCommandHandler finds the item with `FindAsync`, guards with `Guard.Against.NotFound`, calls `Remove` and saves; DeleteTodoListCommandHandler does the same after `SingleOrDefaultAsync`, and removing a list cascades to its items. GetTodosQueryHandler projects every TodoList with `ProjectTo<TodoListDto>`. src/Web/Endpoints/TodoItems.cs maps `DELETE {id}` to the command behind `RequireAuthorization`. The agent adds an `ISoftDeletable` interface in Domain/Common with `IsDeleted`, `Deleted` and `DeletedBy`, implemented by BaseAuditableEntity so TodoList and TodoItem both carry it, and a SoftDeleteInterceptor next to the auditable one that turns a Deleted entry for such an entity into a Modified one with the flag, the timestamp from TimeProvider and the user from IUser, registered the same way in DependencyInjection.cs. A query filter on `IsDeleted` goes on every ISoftDeletable entity in OnModelCreating, so GetTodos and every other query stop seeing deleted rows without a change to their code. Deleting a list marks its items in the same save, which replaces the cascade the database used to do. Two new commands, RestoreTodoList and RestoreTodoItem, find the row with `IgnoreQueryFilters` and clear the flag, with endpoints beside the delete ones.

Tests live in tests/Application.FunctionalTests, where FunctionalTestSetup.cs starts the TestAppHost through Aspire's DistributedApplicationTestingBuilder, waits for the database resource, builds a WebApiFactory on its connection string and resets the database between tests; DeleteTodoItemTests.cs creates a list and an item, sends the delete command and expects `TestApp.FindAsync<TodoItem>` to return null. The agent reads Infrastructure/TestApp.cs to see that FindAsync goes through the context, decides what that assertion means now (the row exists but is hidden), and rewrites it to assert through a filtered query and through `IgnoreQueryFilters` that the item is flagged with a Deleted timestamp and a DeletedBy. New tests cover the list cascade, both restore commands, a restore of an id that was never deleted raising NotFoundException, and GetTodos no longer listing a deleted list.

Then it runs what .github/workflows/build.yml runs: `dotnet restore`, `dotnet build --no-restore --configuration Release` and `dotnet test --no-build --configuration Release`, which takes in the functional tests on the SQLite default the README describes and the Playwright acceptance tests when the client app is built. The description notes that src/Web/ClientApp has an nswag.json, so the generated API client picks up the restore endpoints the next time it is generated.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add soft delete to this ASP.NET Core solution. Read global.json, Directory.Packages.props, src/Domain/Common, src/Domain/Entities, src/Infrastructure/Data/ApplicationDbContext.cs, ApplicationDbContextInitialiser.cs, the Interceptors and Configurations folders, src/Infrastructure/DependencyInjection.cs, the DeleteTodoItem and DeleteTodoList commands, GetTodosQuery, src/Web/Endpoints/TodoItems.cs and TodoLists.cs, tests/Application.FunctionalTests including Infrastructure/TestApp.cs and the delete tests, and .github/workflows/build.yml first. Add an ISoftDeletable interface with IsDeleted, Deleted and DeletedBy on the auditable base entity, a SaveChangesInterceptor in the style of AuditableEntityInterceptor that turns a Deleted entry into a flagged Modified one with the time and user, registered the same way, and a global query filter for every soft-deletable entity in OnModelCreating. Make deleting a list flag its items. Add RestoreTodoList and RestoreTodoItem commands with validators and endpoints beside the delete ones, using IgnoreQueryFilters to find the row. Rewrite the delete tests to assert the row is hidden but flagged, and add functional tests for the cascade, both restores, a restore of an undeleted id and GetTodos hiding a deleted list. Run restore, build and test in Release as the workflow does, and open a pull request that explains the interceptor and quotes the test output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request on its own branch that adds src/Domain/Common/ISoftDeletable.cs, src/Infrastructure/Data/Interceptors/SoftDeleteInterceptor.cs and the two restore commands with their validators and tests, and changes BaseAuditableEntity.cs, ApplicationDbContext.cs, Infrastructure/DependencyInjection.cs, the two delete handlers, src/Web/Endpoints/TodoLists.cs and TodoItems.cs and the existing delete tests. No migration is added, because the initialiser recreates the schema with EnsureCreated; the description says that a fork on migrations needs one `dotnet ef migrations add`.

The description quotes the `dotnet test` run from the sandbox with the functional tests listed, explains why the delete test's null assertion was replaced, and shows the two rows of one deleted list as a filtered query and an unfiltered query see them.

Before merging, a reviewer decides whether restore should need the Administrator role from Domain/Constants/Roles.cs, whether Identity users should ever be soft-deletable (they are left out), and when flagged rows are purged for good, which is a background job for a follow-up on the same session.

## Run it on every entity removed with Remove and SaveChanges

This is a change to start from the terminal and pick up later: one `POST /o/{org}/sessions` with this prompt and the repository in `resources`, and the run reads the interceptors, writes the filter, rewrites the tests and opens the pull request without anyone watching. The sandbox parks with its disk when the turn ends, so `restrict restore to administrators` as a follow-up wakes it with the NuGet cache, the built solution and the branch intact.

A team with several .NET services sends the same body once per repository, one run each, and each run reads that service's own entities and interceptors. Give the API key a `webhook_url` and Rush posts `run.completed` or `run.failed` with the `session_url` when each turn ends. Send a `request_id` with each body so a retried POST returns the run it already started rather than a second one.

## Why run it on Rush?

Soft delete is a small amount of code with a large blast radius: every query in the solution changes meaning, the cascade from list to item has to be done by hand, and a test that used to prove deletion now proves hiding. The agent makes the change where the solution's own interceptors live, reruns the functional tests against the Aspire-hosted database in its sandbox, and the pull request carries the output rather than an assurance.

The record shows how the awkward parts were settled: the transcript has the agent reading TestApp.FindAsync, deciding what the delete test should assert now, and checking the list cascade in a single save. A reviewer who wants a different rule, such as hard-deleting items when their list is deleted, says so and the parked sandbox changes the interceptor.

## Frequently asked questions

### Why an interceptor rather than overriding SaveChangesAsync?

Because the solution already does its auditing that way: AuditableEntityInterceptor is a SaveChangesInterceptor registered as ISaveChangesInterceptor and added to the context's options. A second interceptor follows the pattern a reader of the Infrastructure project already knows.

### What happens to FindAsync and the existing delete test?

The test expected null after a delete. With a query filter the row is hidden from filtered queries but still there, so the agent rewrites the assertion to check both views and relies on the test run, not an assumption, for how FindAsync behaves with the filter.

### Do I need a migration?

Not in this template, where ApplicationDbContextInitialiser drops and recreates the database with EnsureCreated. If your fork uses migrations, add one for the three new columns with dotnet ef migrations add before deploying.

### Can a deleted list or item be restored?

Yes. RestoreTodoList and RestoreTodoItem find the row with IgnoreQueryFilters, clear the flag and save, and are mapped as endpoints beside the delete ones. Restoring an id that was never deleted raises the same NotFoundException the delete commands use.

### Are the items of a deleted list hidden too?

Yes. The interceptor flags a list's items in the same SaveChanges, so GetTodos and any item query stop seeing them, and restoring the list restores its items.

## More ASP.NET Core jobs

- [List Every API Endpoint in an ASP.NET Core App](https://getrush.ai/run/api-endpoint-inventory/aspnet-core/)
- [Explain the Architecture of an ASP.NET Core Solution](https://getrush.ai/run/architecture-overview/aspnet-core/)
- [Fix an ASP.NET Core App Bug From a Datadog Monitor Alert](https://getrush.ai/run/fix-datadog-alerts/aspnet-core/)

## The same job on other stacks

- [Add Soft Delete to an Axum API](https://getrush.ai/run/add-soft-delete/axum/)
- [Add Soft Delete to a Django REST Framework API](https://getrush.ai/run/add-soft-delete/django-rest-framework/)
- [Add Soft Delete to a Drizzle Schema](https://getrush.ai/run/add-soft-delete/drizzle/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
