3

I create a database with two tables in it, then I execute this code, but it does nothing to the tables at all.

private void CreateConstraint(DataSet dataSet, string table1, string table2, string column1,
                              string column2)
{
    string connectionString =
        @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\...\Database1.accdb";
    OleDbConnection connection = new OleDbConnection(connectionString);
    OleDbDataAdapter daf1 = new OleDbDataAdapter("select * from " + table1,connection);
    daf1.Fill(dataSet,table1);

    OleDbDataAdapter daf2 = new OleDbDataAdapter("select * from " + table2,connection);

    daf2.Fill(dataSet,table2);

    ForeignKeyConstraint FornKey = new ForeignKeyConstraint("ForKeyCustOrder",
        dataSet.Tables[table1].Columns[column1],dataSet.Tables[table2].Columns[column2]);

    FornKey.DeleteRule = Rule.Cascade;

    // Add the constraint, and set EnforceConstraints to true.
    dataSet.Tables[table2].Constraints.Add(FornKey);
    dataSet.EnforceConstraints = true;

    dataSet.AcceptChanges();
    daf1.Update(dataSet.Tables[table1]);
    daf2.Update(dataSet.Tables[table2]);
}
Gord Thompson
  • 116,920
  • 32
  • 215
  • 418
Wil
  • 31
  • 1

1 Answers1

1

The OleDbDataAdapter#Update method is for updating the contents of a database table. It does not support making changes to the structure of a database table. For that you will need to execute a DDL (Data Definition Language) statement via an OleDbCommand object:

string sql = 
        "ALTER TABLE tblChild " +
        "ADD CONSTRAINT FK_tblChild_tblParent " + 
        "    FOREIGN KEY (ParentID) " +
        "    REFERENCES tblParent (ID) " +
        "    ON DELETE CASCADE";
using (var cmd = new OleDbCommand(sql, conn))
{
    cmd.ExecuteNonQuery();
}
Gord Thompson
  • 116,920
  • 32
  • 215
  • 418