更新DataTable中的单行

时间:2014-05-09 09:54:06

标签: c# .net caching datatable

TL; DR: 我想更新一个DataTable行,然后重新缓存整个DataTable(DataTable而不仅仅是行),以便我以后可以使用它

我使用缓存来存储我已经用基于MSSQL数据库的SqlAdapter填充的大型DataTable

我使用这个缓存获取DataTable然后用它来显示网页内的表格,这里没什么奇怪的。

但是这个DataTable包含一个用户列表,我希望能够编辑这些用户(在MSSQL数据库中编辑它们),这很容易。

问题是,在每次SQL Update之后,您必须重新缓存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;

1 个答案:

答案 0 :(得分:1)

我认为您可以使用DataRow的ItemArray属性:

void Main()
{
    DataTable tableOld = new DataTable();
    tableOld.Columns.Add("ID", typeof(int));
    tableOld.Columns.Add("Name", typeof(string));

    tableOld.Rows.Add(1, "1");
    tableOld.Rows.Add(2, "2");
    tableOld.Rows.Add(3, "3");

    DataTable tableNew = new DataTable();
    tableNew.Columns.Add("ID", typeof(int));
    tableNew.Columns.Add("Name", typeof(string));

    tableNew.Rows.Add(1, "1");
    tableNew.Rows.Add(2, "2");
    tableNew.Rows.Add(3, "33");

    tableOld.Rows[2].ItemArray = tableNew.Rows[2].ItemArray; //update specific row of tableOld with new values

    //tableOld.Dump();
}