我正在使用C#在Windows窗體上使用SqlDataAdapter
。我有一個BindingSource
將它連接到我的領域與功能記錄遍歷和保存更改回數據庫。使用ADO.NET更新單個記錄SqlDataAdapter
我想給用戶提供更改當前記錄更新數據庫,不寫那些其他記錄製成,但他們留在該集緩存修改(即保存與全部保存)的選項。
我已經把它的工作原理(排序)如下:
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)。
我想我明白了爲什麼發生錯誤的(我做了,現在沒有反映在緩存副本更改數據庫),但不知道如何着手。
是否有這樣做的最佳做法?從一開始就是一個固有的壞主意?
這聽起來像你想使用DataTable – Stig
我其實首先嚐試(使用DataViewRowState.ModifiedOriginal從視圖中創建一個新的'DataTable',通過ID刪除當前記錄的行,使用' DataViewRowState.ModifiedCurrent',將DataTable提交給數據庫,然後將BindingSource鏈接表從之前的狀態恢復到原始狀態,我認爲它看起來不必要的複雜(甚至比這更復雜),我想它會避免併發異常 - 我是否應該再次使用我剛剛描述的方法? –