2014-05-09 55 views
0

TL;博士: 我要更新一個數據錶行,然後重新緩存這整個數據表(數據表不只是行),這樣我就可以更新單行DataTable中

我以後使用它m使用緩存來存儲一個大的DataTable,我用我的MSSQL數據庫填充了一個SqlAdapter

我使用這個緩存來獲取DataTable,然後用它在網頁中顯示一張表,這裏沒有什麼奇怪的。

但是這個DataTable包含一個用戶列表,我希望能夠編輯這些用戶(在MSSQL數據庫中編輯它們),這很容易做到。

問題是,在每個SQL更新之後,您必須重新緩存DataTable(否則它只會在數據庫中更新,但不會在DataTable /網頁中更新),並且由於它非常大,所以非常煩人並且使非常簡單的用戶更新需要很長時間,因爲它還必須通過SQL SELECT來獲取所有帖子,然後重新緩存它

因此,我想在做完DataTable後直接更新該特定行我的SQL更新,這種方式我不必重新獲取整個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; 
+0

ü要更新整行或特定列? –

+0

@ X-Developer整行如你已經看到我在代碼 – HenrikP

+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(); 
} 
+0

是的,最後一部分是我所需要的。謝謝! – HenrikP