//________________________________________________________________________________________________ public static void AddModel(ContactoFormViewModel modelToAdd) { SqlConnection connection = new SqlConnection(); connection = Connect(); string requestsQuery = "INSERT INTO [Requests] (Name, Phone, Email, Message) VALUES (@name, @phone, @email, @message)"; SqlCommand requestsCommand = new SqlCommand(requestsQuery, connection); requestsCommand.Parameters.AddWithValue("@name", modelToAdd.Nombre); requestsCommand.Parameters.AddWithValue("@phone", modelToAdd.Telefono); requestsCommand.Parameters.AddWithValue("@email", modelToAdd.CorreoElectronico); requestsCommand.Parameters.AddWithValue("@message", modelToAdd.Mensaje); try { connection.Open(); requestsCommand.ExecuteNonQuery(); } catch (Exception exc) { Console.WriteLine(exc.Message); throw exc; } }
public static List <ContactoFormViewModel> GetAllModels() { SqlConnection connection = Connect(); string query = "SELECT * FROM [HITEF_Db].[dbo].[Requests]"; List <ContactoFormViewModel> modelList = new List <ContactoFormViewModel>(); SqlCommand cmd = new SqlCommand(query, connection); try { connection.Open(); SqlDataReader connectionDataReader = cmd.ExecuteReader(); if (connectionDataReader.HasRows) //We check if dataReader is NOT empty by checking if it has any rows. { while (connectionDataReader.Read()) //So, as long as it can be read... { ContactoFormViewModel tempModel = new ContactoFormViewModel(); //we populate the properties of a new model tempModel.Nombre = connectionDataReader.GetValue((int)requestsColumns.Name).ToString(); tempModel.Telefono = connectionDataReader.GetValue((int)requestsColumns.Phone).ToString(); tempModel.CorreoElectronico = connectionDataReader.GetValue((int)requestsColumns.Email).ToString(); tempModel.Mensaje = connectionDataReader.GetValue((int)requestsColumns.Message).ToString(); modelList.Add(tempModel); //and finally, we Add that model to the List<> the method will be returning. //At the end, we will have a full List with all the models/records from our Database Requests Table. } } } catch (Exception exception) { throw exception; } finally { connection.Close(); } return(modelList); }