【问题标题】:Schema changes not persisted with OleDbDataAdapter .Update method架构更改未使用 OleDbDataAdapter .Update 方法保留
【发布时间】:2017-10-07 15:35:29
【问题描述】:

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

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

【问题讨论】:

    标签: c# ms-access ado.net oledb oledbdataadapter


    【解决方案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();
    }
    

    【讨论】:

      猜你喜欢
      • 2013-01-28
      • 2021-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 2015-06-04
      • 2022-01-05
      • 2012-04-27
      相关资源
      最近更新 更多