public static void SaveQuestion(QuestionModel question, BindableCollection<TopicModel> topics) { //Connection to the database using (var cnn = new SQLiteConnection(LoadConnectionString())) { byte[] imagen; if (question.Image != null) imagen = ImageModel.BitmapToByte(question.Image); else imagen = null; //Save question data cnn.Open(); SQLiteCommand command = new SQLiteCommand(cnn); command.CommandText = "Insert into Question(QuestionText, Answer) values(@param1,@param2)"; command.CommandType = CommandType.Text; command.Parameters.Add(new SQLiteParameter("@param1",question.QuestionText)); command.Parameters.Add(new SQLiteParameter("@param2", question.Answer)); command.ExecuteNonQuery(); cnn.Close(); //Get the last question ID var num = cnn.Query("SELECT IdQ FROM Question ORDER BY IdQ DESC LIMIT 1").First().IdQ; //Save image SQLiteConnection con = new SQLiteConnection(LoadConnectionString()); SQLiteCommand cmd = con.CreateCommand(); cmd.CommandText = String.Format($"UPDATE Question SET ImageSource = @0 WHERE IdQ={num}"); SQLiteParameter param = new SQLiteParameter("@0", System.Data.DbType.Binary); param.Value = imagen; cmd.Parameters.Add(param); con.Open(); cmd.ExecuteNonQuery(); con.Close(); //Save answers loop int i = 1; foreach (var ans in question.Answers) { //Save answer cnn.Open(); command = new SQLiteCommand(cnn); command.CommandText = "Insert into Answer (AnswerText, Num, Question) values (@param1,@param2,@param3)"; command.CommandType = CommandType.Text; command.Parameters.Add(new SQLiteParameter("@param1", ans)); command.Parameters.Add(new SQLiteParameter("@param2", i)); command.Parameters.Add(new SQLiteParameter("@param3", num)); command.ExecuteNonQuery(); cnn.Close(); i++; } //Add to topic loop foreach (var topic in topics) { int id = topic.IdT; cnn.Execute($"Insert into TopicQuestion (Question,Topic) values ({num},{id})"); UpdateNumberOfQuestions(id); } } }