Search code examples
c#.netsql-serverpetapoco

Updating database in Transaction from List<T>


I have a database table which has 2 columns and I have a List where T has 2 properties.

How can I create a transaction so that I can effectively say:

UPDATE MyTable 
SET ColumnA = List<T> 1st property 
WHERE ColumnB = List<T> 2nd Property

A transaction may not necessarily be needed if one update will get executed but if I have 100 items in my List what will be required to get this working?


Solution

  • You need to execute these update statements in a loop, looping over your list

    using(var connection = new SqlConnection(connectionString)) {
        connection.Open();
        using(var transaction = connection.BeginTransaction("Transaction")) {
            foreach(var item in list) {
                using(var command = connection.CreateCommand()) {
                    command.Transaction = transaction;
                    command.CommandText = // set the command text using item
                    command.ExecuteNonQuery();
                }
            }
            transaction.Commit();
        }
    }