无法使用 getchanges 方法获取最近添加的记录

Unable to get recently added records with getchanges method

这是我的 table:

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

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

这是我的代码:

 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 但我在这一行中得到了 null:

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

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

更新 datatable 后,没有更多待处理的更改,因此 GetChanges return 您按预期取消

参见this MSDN page for DataAdapter.Update()

  1. DataRow.AcceptChanges is called. This will raise both the DataTable.RowChanging and DataTable.RowChanged events for the updated DataRow.

Update() 正在为您调用 AcceptChanges。

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

When invoking AcceptChanges, the EndEdit method is implicitly called to end any edits. If the RowState of the row was Added or Modified, the RowState becomes Unchanged. If the RowState was Deleted, the row is removed.

这就是为什么您的 GetChanges() 调用没有返回任何内容 -- 没有任何变化。

加载数据表后。

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

那么当你 运行 GetChanges 时,它应该 return 插入新的 row

更新:insert操作后使用GetChanges