1
ADO.Net中的ForeignKeyConstraint類的AcceptRejectRule屬性的生命目的是什麼?ADO.Net中ForeignKeyConstraint.AcceptRejectRule的用途?
MSDN文檔沒有足夠的解釋(對我來說)明確其目的。閱讀完文檔後,我認爲將該屬性設置爲None將防止將父表中的任何更改級聯到子表。但是,這個假設被證明是運行下面的代碼錯後:
DataTable table1 = new DataTable("Customers");
table1.Columns.Add(new DataColumn("CustomerID", typeof(int)));
table1.Columns.Add(new DataColumn("CustomerName", typeof(string)));
DataTable table2 = new DataTable("Orders");
table2.Columns.Add(new DataColumn("OrderID", typeof(int)));
table2.Columns.Add(new DataColumn("CustomerID", typeof(int)));
DataSet dataSet = new DataSet();
dataSet.Tables.AddRange(new DataTable[] { table1, table2 });
dataSet.EnforceConstraints = true;
DataRelation dataRelation = new DataRelation("CustomerOrders", table1.Columns["CustomerID"],
table2.Columns["CustomerID"], true);
dataSet.Relations.Add(dataRelation);
Debug.WriteLine("No. of constaints in the child table = {0}", table2.Constraints.Count);
dataRelation.ChildKeyConstraint.AcceptRejectRule = AcceptRejectRule.None;
dataRelation.ChildKeyConstraint.DeleteRule = Rule.Cascade;
dataRelation.ChildKeyConstraint.UpdateRule = Rule.Cascade;
table1.Rows.Add(new object[] { 11, "ABC" });
table1.Rows.Add(new object[] { 12, "XYZ" });
table2.Rows.Add(new object[] { 51, 12 });
table2.Rows.Add(new object[] { 52, 11 });
table2.Rows.Add(new object[] { 53, 11 });
table1.Rows.RemoveAt(0);
table1.AcceptChanges();
table2.AcceptChanges();
Debug.WriteLine("No of rows in the parent table = {0}", table1.Rows.Count);
Debug.WriteLine("No of rows in the child table = {0}", table2.Rows.Count);
上述代碼的輸出是:
子表= 1
否constaints號行父表= 1
沒有在子表中的行= 1
感謝,
d inesh
我也在table2上調用了AcceptChanges(),輸出保持不變,即從子表中刪除了2個相關的行。恐怕我仍然無法瞭解這個物業的目的。請你詳細說明一下「AcceptRejectRule隻影響接受/拒絕命令本身是否級聯,在你的代碼中」? –
因爲'DeleteRule = Rule.Cascade',他們正在被刪除。改爲嘗試設置DeleteRule = Rule.None。 –
在設置DeleteRule = Rule.None然後運行該程序時,出現錯誤:「無法刪除此行,因爲在關係CustomerOrders上實施了約束,並且刪除此行將會疊加子行。」這很好,它符合預期的要求。但是,它並未明確AcceptRejectRule屬性的用途。 –