'Define an entity in EF that keeps related data on delete

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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 RoryF