【问题标题】:Unable to get recently added records with getchanges method无法使用 getchanges 方法获取最近添加的记录
【发布时间】:2016-10-21 15:43:24
【问题描述】:

这是我的桌子:

学生StudentId int PK autoincrement,Name varchar(20)

当我向数据表添加新行并将其更新以将其发送到数据库时,它工作正常,但我试图获取最近添加的行,然后我得到空值。

这是我的代码:

 using (var connection = new SqlConnection("MyConnectionstring"))
            {
                connection.Open();
                SqlDataAdapter adapter = new SqlDataAdapter();
                SqlCommandBuilder builder = new SqlCommandBuilder(adapter);

                adapter.SelectCommand = new SqlCommand("select * from Student", connection);


                DataTable dt = new DataTable();
                adapter.Fill(dt);

                DataRow row = dt.NewRow();
                row["Name"] = "Abc";
                dt.Rows.Add(row);
                adapter.Update(dt);
                var addedRecords = dt.GetChanges(DataRowState.Added); //getting null here
                connection.Close();
            }  

但是我添加了学生Abc,但我在这一行中得到了空值:

var addedRecords = dt.GetChanges(DataRowState.Added); //getting null here

【问题讨论】:

    标签: c# .net datatable ado.net dataadapter


    【解决方案1】:

    this MSDN page for DataAdapter.Update():

    1. DataRow.AcceptChanges 被调用。这将提高两者 更新的 DataTable.RowChanging 和 DataTable.RowChanged 事件 数据行。

    Update() 正在为您调用 AcceptChanges。

    如果我们查看the MSDN page for AcceptChanges()

    在调用 AcceptChanges 时,会隐式调用 EndEdit 方法 结束任何编辑。如果行的 RowState 被添加或修改, RowState 变为未更改。如果 RowState 已删除,则该行 被删除。

    这就是您的 GetChanges() 调用没有返回任何内容的原因——不再有任何更改。

    【讨论】:

      【解决方案2】:

      也许adapter.Update(dt); 之后就没有变化了?

      【讨论】:

      • 你能说一些细节吗?
      【解决方案3】:

      一旦您更新了您的datatable,就没有更多未决的更改,因此GetChanges 按预期返回 null

      【讨论】:

        【解决方案4】:

        加载数据表后。

        你不得不说 Datatable.AcceptChanges(); 初始提交

        然后当你运行GetChanges时,它应该返回插入的新row

        更新:insert操作之后使用GetChanges

        【讨论】:

        • 当我使用这个 Datatable.AcceptChanges();那么我对数据库表的更改不会发生
        猜你喜欢
        • 1970-01-01
        • 2014-05-02
        • 1970-01-01
        • 2020-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-26
        相关资源
        最近更新 更多