【发布时间】:2014-05-09 09:54:06
【问题描述】:
tl;博士: 我想更新一个 DataTable 行,然后重新缓存整个 DataTable(DataTable 不仅仅是行),以便以后可以使用它
我正在使用缓存来存储一个大型 DataTable,我已经根据我的 MSSQL 数据库填充了一个 SqlAdapter
我使用这个缓存来获取 DataTable,然后用它在网页中显示一个表格,这没什么奇怪的。
但是这个 DataTable 包含一个用户列表,我希望能够编辑这些用户(在 MSSQL 数据库中编辑它们),这很容易做到。
问题是,在每次 SQL 更新后,您必须重新缓存 DataTable(否则它只会在数据库中更新,而不会在 DataTable/网页中更新),并且由于它非常大,因此非常烦人并且会导致非常简单的用户更新需要很长时间,因为它还必须通过 SQL SELECT 来获取所有帖子,然后重新缓存它
因此,我想在执行 SQL 更新后直接更新 DataTable 中的特定行,这样我就不必重新获取整个 SQL 表(这是 SQL SELECT 部分,因为这么大)
到目前为止,我已经做到了
//We just updated our user, now we'll fetch that with SQL and put it in a new fresh DataTable(that contains just that one row) - since this is much faster than getting the whole table
//Then we'll use that DataTable containing one fresh row to update our old DataTable and re-cache it
DataTable newDataTable = getUserByID(userID); //Get our just edited DataTable row
DataTable cachedDataTable = getSetUserCache(); //Get our cached DataTable
DataRow oldRow = cachedDataTable.Select(string.Format("id = {0}", userID)).FirstOrDefault(); //Get the old row that contains the correct ID
string test = oldRow["status"].ToString(); //Contains the old and cached value before it got edited
oldRow = newDataTable.Rows[0]; //Update the old row with the new row
string test2 = oldRow["status"].ToString(); //Now it contains the new edited value
//Here I should update the cachedDataTable with the new row updated row
DataRow oldRowAfterUpdated = cachedDataTable.Select(string.Format("id = {0}", userID)).FirstOrDefault(); //Get the old row that now should be updated but isn't
string test3 = oldRowAfterUpdated["status"].ToString(); //Still contains the old and cached value before it got edited
success = updateUserCache(cachedDataTable); //Update the DataTable cache that we'll be using later on
我只看到有关如何更新行的帖子,但实际上如何使用新行更新 DataTable 本身?
解决方案:
cachedDataTable.Select(string.Format("id = {0}", userID)).FirstOrDefault().ItemArray = newDataTable.Rows[0].ItemArray;
【问题讨论】:
-
你想更新整行还是特定列??
-
@X-Developer 你已经可以看到我在代码中所做的整行
-
如果列相同,你不能更新所有列数据???
-
@X-Developer 我想更新一行,然后用它更新 DataTable,以便以后可以使用 DataTable