Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible to add DataRelation to DataSet if child table contains rows that have no parent in parent table in C# / ADO.NET 2.0

Tags:

c#

ado.net

If I fill the DataSet with DataAdapters that select all rows from Orders and Customers and call:

private void CreateRelation() 
{
    // Get the DataColumn objects from two DataTable objects 
    // in a DataSet. Code to get the DataSet not shown here.
    DataColumn parentColumn = 
        DataSet1.Tables["Customers"].Columns["CustID"];
    DataColumn childColumn = 
        DataSet1.Tables["Orders"].Columns["CustID"];
    // Create DataRelation.
    DataRelation relCustOrder;
    relCustOrder = new DataRelation("CustomersOrders", 
        parentColumn, childColumn);
    // Add the relation to the DataSet.
    DataSet1.Relations.Add(relCustOrder);
}

(from http://msdn.microsoft.com/en-us/library/system.data.datarelation.aspx)

there will be a runtime error if there is orders that do not have customers. This might happen when a buggy program has not deleted customer's orders when customer was deleted.

What can I do except put Orders select string a additional where-condition:

CUSTID IN (SELECT DISTINCT CUSTID FROM CUSTOMERS)

OR: is it really that way (that all children have to have parents)? My code might have a bug also. The exception occurs when IN MY CODE I add the relation to filled DataSet. The exception is:

An unhandled exception of type 'System.ArgumentException' occurred in System.Data.dll

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

Thanks & Best Regards - Matti

like image 243
char m Avatar asked Feb 28 '23 07:02

char m


1 Answers

there's an overload on the Add() method that includes a bool value to enforce constraints or not. I think I've used it in the past like this:

DataRelation dr = ds.Relations.Add("name", DataColumnParent, DataColumnChild, false);

EDIT

Sorry, the only overload is on this method signature: http://msdn.microsoft.com/en-us/library/3zy636kc.aspx

DataRelationCollection.Add(String, DataColumn[], DataColumn[], bool)
like image 150
David Fox Avatar answered May 03 '23 03:05

David Fox