Hello everybody,
this is my code I have:
I have read that setting up the CommandText should happen only once and not in a loop... but how do I then get the individually item data from the foreach?
Someone smart enough to refactor that code, that would be nice :)
using (SQLiteTransaction trans = DataAccess.ConnectionManager.BeginTransaction())
{
using (SQLiteCommand com = new SQLiteCommand(DataAccess.ConnectionManager))
{
// How can I add the parameters here if they are only known in the foreach loop?
com.Parameters.Add(new SQLiteParameter("@date", day.SchooldayDate));
com.Parameters.Add(new SQLiteParameter("@periodnumber", period.PeriodNumber));
com.Parameters.Add(new SQLiteParameter("@schoolclasscode", period.SchoolclassCode));
foreach (var week in weekList)
{
foreach (var day in week.Days)
{
foreach (var period in day.Periods)
{
com.CommandText = "Insert into tablename (date,periodnumber,schoolclasscode) Values (@date,@periodnumber,@schoolclasscode)";
}
}
}
com.ExecuteNonQuery();
}
trans.Commit();
}
UPDATE: The solution that works!
using (SQLiteTransaction trans = DataAccess.ConnectionManager.BeginTransaction())
{
using (SQLiteCommand com = new SQLiteCommand(DataAccess.ConnectionManager))
{
com.CommandText = "Insert into lessonday (lessondate,lessonnumber,schoolclasscode) VALUES (@lessondate,@lessonnumber,@schoolclasscode)";
SQLiteParameter p1 = new SQLiteParameter("@lessondate", DbType.DateTime);
SQLiteParameter p2 = new SQLiteParameter("@lessonnumber", DbType.Int32);
SQLiteParameter p3 = new SQLiteParameter("@schoolclasscode", DbType.String);
com.Parameters.Add(p1);
com.Parameters.Add(p2);
com.Parameters.Add(p3);
foreach (var week in weekList)
{
foreach (var day in week.Days)
{
p1.Value = day.SchooldayDate;
foreach (var period in day.Periods)
{
p2.Value = period.PeriodNumber;
p3.Value = period.SchooclassCode;
com.ExecuteNonQuery();
}
}
}
}
trans.Commit();
}
}