我创建了一个包含两个表的数据库,然后执行了这段代码,但它对这些表完全没有任何作用。

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]);
}

最佳答案

OleDbDataAdapter#Update方法用于更新数据库表的内容。它不支持对数据库表的结构进行更改。为此,您将需要通过OleDbCommand对象执行DDL(数据定义语言)语句:

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();
}

关于c# - 使用OleDbDataAdapter .Update方法无法持久保存模式更改,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46622010/

10-12 06:42