There is a console app where I have a sql select statement with some inner joins.I want for every result of this statement to update a column of one of these tables with a new value using C#.
Here what I've already tried:
using System;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace MyProgram
{
class Program
{
private static SqlConnection _connection;
private static SqlTransaction _transaction;
static void Main(string[] args)
{
using (var connection = new SqlConnection())
{
try
{
connection.ConnectionString = ConfigurationManager.ConnectionStrings["myConfig"].ConnectionString;
connection.Open();
_connection = connection;
using (var command = connection.CreateCommand())
{
command.CommandText =
"My Select sql stament with inner joins";
using (var reader = command.ExecuteReader())
{
var indexOfColumn3 = reader.GetOrdinal("IDExtObject");
while (reader.Read())
{
_transaction = _connection.BeginTransaction("UpdateTransaction");
command.Transaction = _transaction;
var extId = reader.GetValue(indexOfColumn3).ToString();
string finalId = "Something new...";
try
{
UpdateIdSqlTransaction(extId, finalId);
_transaction.Commit();
}
catch (Exception)
{
_transaction.Rollback();
}
}
}
}
}
catch (Exception)
{
if (_transaction != null)
_transaction.Rollback();
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
Console.ReadLine();
}
private static void UpdateIdSqlTransaction(string objectId, string newId)
{
using (_connection)
{
SqlCommand command = _connection.CreateCommand();
command.Connection = _connection;
var commandText = "The update SQL statement...";
command.CommandText = commandText;
command.Parameters.AddWithValue("@ID", objectId);
command.Parameters.AddWithValue("@newId", newId);
command.ExecuteNonQuery();
}
}
}
}
The problem is that I am getting this exception:
{"New transaction is not allowed because there are other threads running in the session."}
What is the problem and how can I achieve this?