gpt4 book ai didi

c# - OleDbDataAdapter .Update 方法未保留架构更改

转载 作者:行者123 更新时间:2023-11-30 17:32:29 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com