AcceptRejectRule类的ForeignKeyConstraint属性在ADO.Net中的作用是什么?
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
谢谢,
迪内什
发布于 2012-05-23 12:42:55
为了避免级联,需要将DeleteRule和UpdateRule设置为Rule.None。
我不确定,但我认为AcceptRejectRule只影响接受/拒绝命令本身是否是级联的。在您的代码中,我猜想更改是级联的(因为DeleteRule和UpdateRule就是这样设置的),但是只有table1上的更改被接受;table2上的更改没有被接受。
发布于 2018-09-01 17:41:25
这是我的理解。假设您有一个父级子关系,并将relation.acceptrejectrule设置为级联。您还将dataadapter.acceptchangesduringupdate设置为true,如果您修改父记录和子记录,然后对父记录执行dataadapter.update,则父记录和子记录将“接受”,如果在子记录上执行subsequent dataadapter.update,则不会更新任何内容(因为“接受”是从父记录级联到子记录的)。所以你的父母得到了更新,但没有孩子的记录。可能的解决方案是先更新子relation.acceptrejectrule,然后更新父级,或者简单地将设置为none。这样做,“接受”将不会级联到子recs,您将能够更新它们。当您对子dataadapter.acceptchangesduringupdate进行更新时,它们也将被“接受”,因为您已经将该true设置为true。当然,您可以将acceptchangesduringupdate设置为false,并执行manual dataset.acceptchanges以接受数据集中的所有更改。但是,如果这样做,请确保您已经对数据集中的所有表进行了更新。
我只是在这里根据我的测试来说明我认为正在发生的事情。如果其他人知道的不一样,请跳进去。
https://stackoverflow.com/questions/10719977
复制相似问题