Architect's Log

I'm a Cloud Architect. I'm highly motivated to reduce toils with driving DevOps.

更新エラー発生のログを出力し、残りのレコードの更新を続行する

更新エラー発生のログを出力し、残りのレコードの更新を続行するサンプルを紹介します。
サンプルではTableAdapterを使用していますが、DataAdapterを使用していれば同じように実装できます。

ソースコード

// using System;
// using System.Data;
// using System.Data.SqlClient;

private void Update(SqlConnection connection, DataTable dataTable) {
    using (HogeTableAdapter tableAdapter = new HogeTableAdapter()) {
        tableAdapter.Connection = connection;
        tableAdapter.DataAdapter.ContinueUpdateOnError = true;
        tableAdapter.DataAdapter.RowUpdated += DataAdapter_RowUpdated;
        tableAdapter.Update(dataTable);
    }
}

void DataAdapter_RowUpdated(object sender, SqlRowUpdatedEventArgs e) {
    if(e.Status != UpdateStatus.ErrorsOccurred)
        return;

    Console.WriteLine("レコードの更新に失敗しました。"  + e.Errors.ToString());
}