gpt4 book ai didi

c# - 为什么这段代码只循环两次?

转载 作者:行者123 更新时间:2023-12-02 11:12:23 25 4
gpt4 key购买 nike

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

最佳答案

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

关于c# - 为什么这段代码只循环两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10629805/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com