I have a loop which goes through each item a list and adds it to the database. The code below is a method which I call when a button is clicked on a WPF form. It gets an ID value and a list of Steps(DTO) from app.xaml.cs and puts the data from the list into a database.
using (SQLiteConnection sqConnection = getDatabaseConnection())
{
SQLiteCommand addItemCommand = sqConnection.CreateCommand();
sqConnection.Open();
SQLiteTransaction stepTrans;
// Start a local transaction
stepTrans = sqConnection.BeginTransaction(System.Data.IsolationLevel.ReadCommitted);
// Assign transaction object for a pending local transaction
addItemCommand.Transaction = stepTrans;
addItemCommand.Connection = sqConnection;
foreach (Step step in StepsGlobal)
{
string sqAddItem = String.Format
("INSERT INTO Steps(ID, RecipeID, Description, StepTime, Dependency, Priority, Type) Values(null, '{0}', '{1}', '{2}', '{3}', '{4}', '{5}')",
recipeID, step.Description, step.StepTime, step.Dependency, step.Priority, step.Type);
addItemCommand.CommandText = sqAddItem;
addItemCommand.ExecuteNonQuery();
stepTrans.Commit();
}
However, It only works for the first two items and I get the following error if the list contains more than two items.
A first chance exception of type 'System.ArgumentNullException' occurred in
System.Data.SQLite.dll
System.ArgumentNullException: Value cannot be null.
Parameter name: No connection associated with this transaction
at System.Data.SQLite.SQLiteTransaction.IsValid(Boolean throwError)
at System.Data.SQLite.SQLiteTransaction.Commit()
at Project.Methods.addStepsToDatabase()
Best guess is that stepTrans.Commit…commits the transaction and invalidates the object. You will need to begin a new transaction after you commit the current one.