简体   繁体   English

在 EF 中定义一个实体,在删除时保留相关数据

[英]Define an entity in EF that keeps related data on delete

I have two entities, User and StockMovement.我有两个实体,User 和 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.在我的系统中,用户可以从存储中添加或删除库存,在这样做时,应该创建一个 StockMovement,引用所述用户并包含有关用户执行的移动的详细信息。

I also want this StockMovement to persist in my Database even if the user is deleted.我还希望这个 StockMovement 在我的数据库中保留,即使用户被删除也是如此。 Meaning if my user gets deleted, the StockMovements that reference him should be kept.这意味着如果我的用户被删除,引用他的 StockMovements 应该被保留。

I'm using EF to handle my persistance.我正在使用 EF 来处理我的持久性。 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.这样,当我删除一个用户时,由于 StockMovement 对用户有一个外键约束,我的 StockMovement 实体将丢失该用户,使其变得无用。 But I want to keep the Username of the deleted User in the StockMovement.但我想在 StockMovement 中保留已删除用户的用户名。

Is there any way to achieve this behaviour?有什么办法可以实现这种行为吗?

I'd suggest not actually deleting the user.我建议不要真正删除用户。 Instead, mark them as deleted .相反,将它们标记为 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.如果您需要删除他们的个人信息 (GDPR),您可以对其进行编辑(将他们的部分信息替换为 *** 或其他内容)并仍然保留数据库记录。 This technique is called " soft delete ".这种技术称为“软删除”。

Here's an article about soft deleting entities in EF core that might help:这是一篇关于在 EF 核心中软删除实体的文章,可能会有所帮助:

Soft Deleting in Entity Framework Core Entity Framework Core 中的软删除

To prevent cascading deletes in EF the FK must be nullable (Guid?) as far as i'm aware, ie 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.为了防止 EF 中的级联删除,据我所知,FK 必须可以为空(Guid?),即 Stock 表中的 FK 必须设置为 Null,然后才能删除用户 object 以防止这种情况发生,否则会导致引用大多数数据库中的约束冲突。 Theres some pretty good documentation for basic stuff:有一些非常好的基本内容文档:

https://learn.microsoft.com/en-us/ef/core/saving/cascade-delete https://learn.microsoft.com/en-us/ef/core/saving/cascade-delete

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM