简体   繁体   English

C#,实体框架和删除SQL Server 2008中的子寄存器

[英]C#, Entity Framework and delete child registers in SQL Server 2008

I know that in SQL Server I can use delete on cascade when I delete a parent row in a table, but in some places I read that is better to implement this logic in the application (repository) instead of delete on cascade in SQL Server. 我知道在SQL Server中,当我删除表中的父行时,可以在层叠上使用delete,但是在某些地方,我读到最好在应用程序(存储库)中实现此逻辑,而不是在SQL Server中在层叠上删除。

So I have two questions. 所以我有两个问题。 First, if I don't use on delete cascade in SQL Server, how to solve this situation with Entity Framework. 首先,如果我不使用SQL Server中的删除级联,如何使用Entity Framework解决这种情况。

  1. user A adds the parent register and its children to the context 用户A将父级寄存器及其子级添加到上下文中
  2. user B adds a new child to the parent register. 用户B向父级寄存器添加一个新的子级。 So user A does not have this child in the context 因此,用户A在上下文中没有这个孩子
  3. user A deletes the parent and all the children that are loaded in his context. 用户A删除其上下文中加载的父级和所有子级。 These children do not include the new child added by user B. 这些子项不包括用户B添加的新子项。

Well, in practice, there is no problem, when user A tries to delete the parent, there is an exception for referential integrity, and the need to load all its children and try again. 好吧,实际上,这没有问题,当用户A尝试删除父级时,存在引用完整性异常,并且需要加载其所有子级并重试。

This is an extra work for SQL Server, because it needs to send to the user A all the registers again. 这是SQL Server的一项额外工作,因为它需要再次将所有寄存器发送给用户A。

If I use delete on cascade in SQL Server, this problem does not exist, so I think is a good option. 如果我在SQL Server的级联上使用delete,则不存在此问题,因此我认为这是一个不错的选择。

So my second question is, is a good idea to use on delete cascade in SQL Server (or other database) or is better to implement this case in the business logic (repository)? 所以我的第二个问题是,在SQL Server(或其他数据库)中的删除级联上使用是个好主意,还是在业务逻辑(存储库)中实现这种情况更好?

Thanks. 谢谢。

It's a matter of personal preference - I hear valid arguments for both options. 这是个人喜好问题-我听到两个选项的有效论点。

What is more obvious, more understandable to you? 有什么更明显,更容易理解的?

  • Do you prefer to have automagic deletion? 您喜欢自动删除吗? Then use ON DELETE CASCADE 然后使用ON DELETE CASCADE

  • or do you prefer to be in full control of these situations to know exactly when and what is being deleted? 还是您希望完全控制这些情况以确切地知道何时删除什么内容? Then implement it in your own custom code 然后以您自己的自定义代码实现

There's no right or wrong, no "better" or "worse" - it's more about your own personal preference and how you feel more comfortable with the code. 没有对与错,没有“更好”或“更糟”-这更多是关于您个人的喜好以及您对代码的感觉如何。

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

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