I have two entities, User and StockMovement. In my system the User can add or remove stock from storage, and in doing so, a StockMovement should be created, referencing said User and containing details about the movement executed by the User.
I also want this StockMovement to persist in my Database even if the user is deleted. Meaning if my user gets deleted, the StockMovements that reference him should be kept.
I'm using EF to handle my persistance. And with that, when I delete an User, as a StockMovement has a foreign key constraint to User, my StockMovement entity would be missing the User, rendering it useless. But I want to keep the Username of the deleted User in the StockMovement.
Is there any way to achieve this behaviour?
CodePudding user response:
As Michal stated in his comment, performinga soft Delete is the solution I'm after. Be sure to check out the article provided as it's very informative on the topic. Article about Soft Deleting in EF Core
CodePudding user response:
To prevent cascading deletes in EF the FK must be nullable (Guid?) as far as i'm aware, i.e the FK in the Stock table must be set to Null before deleting the User object to prevent this or else it would cause a referential constraint violation in most DBs. Theres some pretty good documentation for basic stuff:
https://docs.microsoft.com/en-us/ef/core/saving/cascade-delete
CodePudding user response:
I'd suggest not actually deleting the user. Instead, mark them as deleted. If you're required to delete their personal details (GDPR), you can redact it (replace a part of their details with *** or something) and still keep the database record. This technique is called "soft delete".
Here's an article about soft deleting entities in EF core that might help: