0

DataTable.Update メソッドを利用して SQL データ ソースを更新しようとしています。以下は、更新を実行するメソッドのコードです。

string connString = "SQL connection string...this works.";
string sqlSelect = "SELECT Payment, Amount, Date, Month, StartDate, EndDate, FROM Payment";

private void updateDataSource(DataTable dt) {
    SqlDataAdapter da = new SqlDataAdapter(sqlSelect, connString);
    SqlCommandBuilder cb = new SqlCommandBuilder(da);
    int result = 0; // store the result of dt.Update

    // copy over any rows from dt that have a payment date
    DataTable temp = dt.Clone(); 
    foreach (DataRow dr in dt.Rows) {
        if (dr.ItemArray[5].ToString() != "") // if payment date is not empty
            temp.ImportRow(dr);
    }

    da.ContinueUpdateOnError = true; // this forces an insert but does not update any other records

    try {
        result = da.Update(temp);
    } catch (DBConcurrencyException dbce) {
        alertUser(
            @"There was an error updating the database.\n" +
            dbce.Message + @"\n" +
            @"The payment type id for the row was: " + dbce.Row.ItemArray[1] + @"\n" +
            @"There were " + temp.Rows.Count + @" rows in the table to be updated.\n");
    }

    if (result == temp.Rows.Count) {
        alertUser("Successful update."); // alert the user
        btnSearchCancel_Click(null, null);
    }

    // store updated data in session variable to store data between posts to server
    Session["gv"] = dt;
}

上記のメソッドは、ユーザーが [テーブルの更新] ボタンをクリックすると呼び出されます。
何が起こっているかは、与える前にda.ContinueUpdateOnError = truetry catchテーブルにレコードが更新/挿入されないことですDBConcurrencyException。 を追加した後、はエラーなしで続行されますが、 の最初の行はまだ更新されませんが、 の 2 番目の行が挿入されます。Concurrency violation: the UpdateCommand affected 0 of the expected 1 records.
da.ContinueUpdateOnError = trueda.Update()DataTable dtdt

さらに奇妙なのは、更新を呼び出して 20 行以下のテーブルを渡すと、更新が完全に実行され、2 行または 3 行が更新され、2 行または 3 行が挿入されることです。2 行のテーブルを渡して更新を呼び出すと、例外がスローされます。2 つの異なるテーブルの構造は同じです。

4

1 に答える 1