How to implement soft-delete #404
Replies: 4 comments 2 replies
-
Thanks for sharing @RobertSundstrom 😊 Have a nice coding. |
Beta Was this translation helpful? Give feedback.
-
Perhaps this can be moved to wiki instead? Issue is mostly used for tracking item that need to be followed up. I'm afraid, people can't find this useful tutorial when this issue closed. |
Beta Was this translation helpful? Give feedback.
-
Thanks for sharing, I've enabled discussions so we can move it over to there |
Beta Was this translation helpful? Give feedback.
-
I want to add a small remark to this. You cannot use a composite primary key and just slap soft-delete on it. I ran into this issue. I still wanted the database table to reflect the uniqueness of the data. The codesituation is very simple: There are Vehicles and VehicleActions. A Vehicle can have multiple VehicleActions assigned to it but the same action only once. That's why my first instinct was to just havethe VehicleActionAssignments table have a composite key. This was my not working code: public class Vehicle : AuditableSoftDeleteEntity
{
public int VehicleId { get; set; }
//Omitted
} public class VehicleAction : AuditableSoftDeleteEntity
{
public int VehicleActionId { get; set; }
//Omitted
} public class VehicleActionAssignment : AuditableSoftDeleteEntity
{
public int VehicleId { get; set; }
public int VehicleActionId { get; set; }
//Omitted
} And in OnModelCreating: modelBuilder.Entity<VehicleActionAssignment>()
.HasKey(v => new { v.VehicleActionId, v.VehicleId }); Whenever a VehicleActionAssignment gets deleted, it disappears from the frontend. It remains in the database of course. When the user now decides to add that same VehicleActionAssignment back again, it will throw an error. What I did to resolve this issue is the following: First I had to add a regular primary key to VehicleActionAssignments public class VehicleActionAssignment : AuditableSoftDeleteEntity
{
public int Id { get; set; }
public int VehicleId { get; set; }
public int VehicleActionId { get; set; }
//Omitted
} I still wanted the database to force uniqueness of VehicleId and VehicleActionId pairs but have as many deleted same pairs as I want. So what you can do is use HasFilter. modelBuilder.Entity<VehicleActionAssignment>()
.HasIndex(v => new { v.VehicleActionId, v.VehicleId })
.HasFilter("Deleted IS NULL")
.IsUnique(); It now forces the pairs to be unique only when the Deleted field is null. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I just want to share how I ended up implementing soft-delete. I wanted to keep it simple.
Feedback is appreciated!
Steps
ISoftDelete interface
Define the interface:
Implement the interface:
Modify DbContext
Add this to the
SaveChangesAsync
method in your DbContext:Entity Model Configuration
Configure Query Filter:
Beta Was this translation helpful? Give feedback.
All reactions