我创建了一个包含两个表的数据库,然后执行此代码,但它根本不对表做任何事。
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]);
}
答案 0 :(得分:1)
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();
}