1

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?

5
  • 1
    I'd suggest not actually deleting the user. Instead, mark them as deleted. If you're required to delete their personal details, you can redact it (replace a part of their details with *** or something). Commented Mar 3, 2022 at 15:58
  • 1
    This article might help: spin.atomicobject.com/2019/01/29/… Commented Mar 3, 2022 at 16:20
  • Thanks, this is what I was aiming to achieve! The article also proved quite helpful. Commented Mar 3, 2022 at 16:27
  • I'm happy to help! Commented Mar 3, 2022 at 17:28
  • I've added an answer, please mark it as an accepted answer if you found it helpful. Commented Mar 3, 2022 at 17:34

2 Answers 2

1

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:

Soft Deleting in Entity Framework Core

Sign up to request clarification or add additional context in comments.

Comments

0

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://learn.microsoft.com/en-us/ef/core/saving/cascade-delete

1 Comment

Thanks for your answer, but that is not quite what I'm aiming to achieve. What I need is more in line with what @Michal commented.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.