An IsDeleted flag marks an entity as deleted without removing its database row. This soft-delete approach hides records from the application while preserving data and avoiding many referential-integrity problems. section 12.4.4
Use the flag safely by following these steps:
- Add a Boolean property such as `public bool IsDeleted { get; set; }` to the entity. section 12.4.4
- Implement deletion as an update: load the entity, set `IsDeleted = true`, and call `SaveChangesAsync()`. section 12.4.4
- Exclude flagged entities from every query, or configure an EF Core global query filter to apply the condition at the model level. section 12.4.4
- Treat this as a practical pattern rather than a universal rule; personally identifying information may need to be scrubbed instead. section 12.4.4
Listing 12.10 Marking entities as deleted in EF Core
public async Task DeleteRecipe(int recipeId)
{
var recipe = await _context.Recipes.FindAsync(recipeId); #1
if(recipe is null) { #2
throw new Exception("Unable to find the recipe"); #2
} #2
recipe.IsDeleted = true; #3
await _context.SaveChangesAsync(); #4
}
Shows the complete EF Core delete operation, including entity lookup, flag assignment, and saving the update. section 12.4.4
