我正在SqlDataAdapter
使用 C# 处理 Windows 窗体。我BindingSource
通过功能记录遍历将它链接到我的字段并将更改保存回数据库。
我想为用户提供使用对当前记录的更改来更新数据库的选项,而不是将所做的更改写入其他记录,而是将它们保存在缓存的修改集中(即保存与全部保存)。
我汇总了以下有效的(有点):
SqlCommand updateCurrent = new SqlCommand("UPDATE Table SET Attribute = @attribute WHERE ID = @currentRecord", sqlConnection)
updateCurrent.Parameters.AddWithValue("@currentRecord", bindingSource.GetItemProperties(null)["ID"].GetValue(bindingSource.Current));
updateCurrent.Parameters.AddWithValue("@attribute", bindingSource.GetItemProperties(null)["Attribute"].GetValue(bindingSource.Current));
updateCurrent.ExecuteNonQuery();
它的工作原理是更新当前显示的记录(并且仅更新该记录),但是当稍后调用常规更新函数时,它会导致System.Data.DBConcurrencyException
(UpdateCommand 影响预期的 1 条记录中的 0 条)。
我想我理解为什么会发生错误(我对数据库进行了更改,但现在没有反映在缓存副本中),但不知道如何继续。
是否有这样做的最佳实践?开始是一个天生的坏主意吗?