使用外键从绑定源中删除行

Delete rows from binding source with foreign key

我有一个包含 2 个 table 的数据源,一个 projectDiamter 和另一个 diameterSet。 ProjectDiameter id 包含主键并且 diameterset 具有具有相同键的外键约束。

现在,当我从 projectdiameter table diameterset DataGridView 的 select 行得到相应的过滤。我在 diameterset 中有很多行(比如说 15000 只用于 selected 项目),我想在按下删除按钮时删除它们。

我想知道从 DataGridView 和 SQL table 中删除它的最快方法是什么。

我尝试了以下代码,但想检查是否有更好的方法来获得相同的代码。

FKProjectDiameterBindingSource.MoveFirst()
For j As Int16 = 0 To FKProjectDiameterBindingSource.Count - 1
    For i As Int16 = 0 To FKDiameterDiameterSetBindingSource.Count - 1
        FKDiameterDiameterSetBindingSource.Clear()
        FKDiameterDiameterSetBindingSource.MoveFirst()
        FKDiameterDiameterSetBindingSource.RemoveCurrent()
    Next
    FKProjectDiameterBindingSource.MoveNext()
Next

Me.Validate()
DiameterTableAdapter.Update(RSM3DDB1.Diameter)
DiameterSetTableAdapter.Update(RSM3DDB1.DiameterSet)

数据库中是否正式存在外键关系?也就是说,SQL中是否定义了实际关系?如果是这样,我建议将该关系设置为 CASCADE DELETE,然后您所要做的就是在更新 Diameter 后调用 DiameterSetTableAdapter.UPDATE。

关于 CASCADE DELETE 的一个很好的解释在这里 https://www.mssqltips.com/sqlservertip/2365/sql-server-foreign-key-update-and-delete-rules/ 请注意,关键字只是 "Cascade" 但您将其应用于 DELETE,文章解释 ("It is not necessary that the same rule be applied for both update and delete operations. There may be different rules for each of the update and delete operations on a single FK constraint.")

如果关系不是正式的,也就是说它在逻辑上存在但没有强制执行,那么我会在 Diameter table 上放置一个触发器,并在该触发器中删除 DiameterSet 中的所有行,其中DiameterID 等于删除的DiameterID。请注意,在触发器中,修改(而不是删除)的行将同时出现在 INSERTED 和 DELETED 临时 table 中,因此您必须采取措施确保您没有删除引用 a 的行修改后的直径。

如果您采用第二种方法,您仍然可以 运行 VB 中 2 table 适配器上的 2 个更新过程,只是 [=26= 中的编码更多] 而不是设置 CASCADE DELETE。

这两种方法都比 VB 中的方法更有效,如果您有数百行受到影响,它可以加起来。

使用其中任何一个也具有原子性的优势,而您的方法则不然。