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 父表中的行数= 1 子表中没有行= 1
谢谢, 迪内希
要避免级联,您需要将DeleteRule
和UpdateRule
设置为Rule.None
。
我不确定,但我相信AcceptRejectRule
只影响接受/拒绝命令本身是否级联。在你的代码中,我猜测这些变化是级联的(因为这是DeleteRule
和UpdateRule
的设置方式),但只有table1
的变化才被接受; table2
的变化尚未被接受。
这是我的理解。假设您有父子关系,并将relation.acceptrejectrule
设置为级联。您还将dataadapter.acceptchangesduringupdate
设置为true
,如果您修改父级和子级记录,然后首先在父级上执行dataadapter.update
,父级和子级记录将被“接受”,如果您对子级记录执行subsequent dataadapter.update
,则不会更新任何内容(因为“接受”是从父母到儿童记录的级联)。所以你的父母得到了更新,但没有更新子记录。可能的解决方案是首先更新子recs,然后更新父项,或者简单地将relation.acceptrejectrule
设置为none。通过这样做,“接受”不会级联到子recs,你将能够更新它们。当你对孩子们进行更新时,他们也将被“接受”,因为你将dataadapter.acceptchangesduringupdate
设置为true
。当然,您可以将acceptchangesduringupdate
设置为false
并执行manual dataset.acceptchanges
以接受数据集中的所有更改。但是,如果这样做,请确保已对数据集中的所有表进行了更新。
我只是在这里根据我的测试说明我认为发生了什么。如果有其他人知道不同,请跳进去。