I am trying to enter a list of data objects to my table using a loop. But during the loop, the logic abruptly stops with this error:
There is already an open DataReader associated with this Command which must be closed first.
Here's my code:
List<TransactionAccount> accounts = new List<TransactionAccount>();
try
{
using (con = new SqlConnection(connectionString))
{
string query = "INSERT INTO Accounts (name, category) VALUES (@name, @category)";
cmd = new SqlCommand(query, con);
con.Open();
foreach (TransactionAccount account in accounts)
{
cmd.Parameters.AddWithValue("@name", account.name);
cmd.Parameters.AddWithValue("@category", account.category);
int exec = cmd.ExecuteNonQuery();
}
con.Close();
}
}
catch (Exception ex)
{
}
The error doesn't make sense because I close the connection at the end of the loop. What should I change here?