1

我有一个循环遍历列表中的每个项目并将其添加到数据库中。下面的代码是我在 WPF 表单上单击按钮时调用的方法。它从 app.xaml.cs 获取 ID 值和 Steps(DTO) 列表,并将列表中的数据放入数据库。

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();
        }

但是,它仅适用于前两项,如果列表包含两个以上的项目,我会收到以下错误。

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() 
4

1 回答 1

2

最好的猜测是 stepTrans.Commit... 提交事务并使对象无效。提交当前事务后,您将需要开始新事务。

于 2012-05-17T04:26:20.000 回答