开发者

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

开发者 https://www.devze.com 2022-12-24 07:57 出处:网络
If I fill the DataSet with DataAdapters that select all rows from Orders and Customers and call: private void CreateRelation()

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("CustomersOrde开发者_JS百科rs", 
        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


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消