ADO.Net中ForeignKeyConstraint.AcceptRejectRule的目的?

问题描述 投票:1回答:2

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

谢谢, 迪内希

c# .net ado.net
2个回答
1
投票

要避免级联,您需要将DeleteRuleUpdateRule设置为Rule.None

我不确定,但我相信AcceptRejectRule只影响接受/拒绝命令本身是否级联。在你的代码中,我猜测这些变化是级联的(因为这是DeleteRuleUpdateRule的设置方式),但只有table1的变化才被接受; table2的变化尚未被接受。


0
投票

这是我的理解。假设您有父子关系,并将relation.acceptrejectrule设置为级联。您还将dataadapter.acceptchangesduringupdate设置为true,如果您修改父级和子级记录,然后首先在父级上执行dataadapter.update,父级和子级记录将被“接受”,如果您对子级记录执行subsequent dataadapter.update,则不会更新任何内容(因为“接受”是从父母到儿童记录的级联)。所以你的父母得到了更新,但没有更新子记录。可能的解决方案是首先更新子recs,然后更新父项,或者简单地将relation.acceptrejectrule设置为none。通过这样做,“接受”不会级联到子recs,你将能够更新它们。当你对孩子们进行更新时,他们也将被“接受”,因为你将dataadapter.acceptchangesduringupdate设置为true。当然,您可以将acceptchangesduringupdate设置为false并执行manual dataset.acceptchanges以接受数据集中的所有更改。但是,如果这样做,请确保已对数据集中的所有表进行了更新。

我只是在这里根据我的测试说明我认为发生了什么。如果有其他人知道不同,请跳进去。

© www.soinside.com 2019 - 2024. All rights reserved.