ADO.NET: Adding DataRelation to a DataSet; which is parent and which is child?

11,170

Solution 1

Wow no one had the right answer ....

The problem is that the example you were reading is under the label "Step 3 - Retrieve Data and Create Nested Relationships".

If you would like to add a relation between two columns of the SAME TABLE (nested), then you must set the 'Nested" variable to true(before adding it) as is shown on his website.

relation.Nested = true;
ds.Relations.Add(relation);

Solution 2

the parent-child relationship is also called a one-to-many relationship, where the 'one' is the parent and the 'many' is the child

the child has a column that holds the key of the parent (aka the "foreign key" column)

in your example, it probably does not like nulls for the parent id; passing false to avoid enabling constraints will likely make the error go away

Share:
11,170

Related videos on Youtube

mistertodd
Author by

mistertodd

Any code is public domain. No attribution required. జ్ఞా <sup>🕗</sup>🕗 Yes, i do write i with a lowercase i. The Meta Stackexchange answer that I am most proud of

Updated on April 16, 2022

Comments

  • mistertodd
    mistertodd about 2 years

    Consider an SQL Server table containing:

    ID   ParentID   Text
    ===  =========  =============
    1    (null)     Product
    2    (null)     Applications
    3    1          Background
    4    1          Details 
    5    2          Mobile
    

    i fill a SqlDataSet with the table, and now i want to add the Parent-Child relation to the DataSet:

    public DataRelation(
        string relationName,
        DataColumn parentColumn,
        DataColumn childColumn,
        bool createConstraints
    )
    

    Now this guy uses:

    DataRelation relation = newDataRelation("ParentChild",
        ds.Tables[0].Columns["ID"], //parentColumn
        ds.Tables[0].Columns["ParentID"] //childColumn, 
        true //createConstraints
    );
    

    But when i do that i get the exception:

    This constraint cannot be enabled 
    as not all values have corresponding parent values.
    

    People have suggested passing false for createConstraints; but then why does it work for him?

    And what is a child and what is a parent anyway? i would have thought the child column is the column that needs pointing to a parent, and parent column is the thing that does the pointing, which would reverse the relation:

    DataRelation relation = newDataRelation("ParentChild",
        ds.Tables[0].Columns["ParentID"], //parentColumn
        ds.Tables[0].Columns["ID"], //childColumn
        true //createConstraints
    );
    

    So which is it? Why does his work? What's with the exception? Why can he create the constraint when he has nulls?

    God it's hot in here.

  • Mass Dot Net
    Mass Dot Net about 12 years
    This is exactly what I needed to know -- MSDN wouldn't give me a straight answer, as usual. tyvm!