Esempio n. 1
0
 public ActionResult Salvar(Models.Votacao entidade)
 {
     string stringConexao = @"Data Source=den1.mssql6.gear.host;Initial Catalog=avaliacao;user Id=avaliacao;Password=Uc3~!e0bw2e3";            using (var conn = new SqlConnection(stringConexao))
     {
         var lista          = CriarListaVotos();
         var listaExistente = lista.Where(x => x.Nome == entidade.Nome);
         if (listaExistente.Count() > 0)
         {
             return(RedirectToAction("Index", new { Sucesso = false }));
         }
         else
         {
             entidade.Id = lista.Count == 0
                 ? 1
                 : lista.OrderByDescending(item => item.Id).FirstOrDefault().Id + 1;
             string     sql = "INSERT INTO Votacao (id,Nome,Voto,Idade) VALUES (@id,@Nome,@voto,@Idade)";
             SqlCommand cmd = new SqlCommand(sql, conn);
             cmd.Parameters.AddWithValue("@id", entidade.Id);
             cmd.Parameters.AddWithValue("@Nome", entidade.Nome);
             cmd.Parameters.AddWithValue("@voto", entidade.Voto);
             cmd.Parameters.AddWithValue("@Idade", entidade.Idade);
             try
             {
                 conn.Open();
                 cmd.ExecuteNonQuery();
             }
             catch (Exception e)
             {
                 throw e;
             }
             return(RedirectToAction("Index"));
         }
     }
 }
Esempio n. 2
0
        private List <Models.Votacao> CriarListaVotos()
        {
            string stringConexao        = @"Data Source=den1.mssql6.gear.host;Initial Catalog=avaliacao;user Id=avaliacao;Password=Uc3~!e0bw2e3";
            string sql                  = "Select id,Nome,Idade,Voto from Votacao";
            List <Models.Votacao> lista = new List <Models.Votacao>();

            using (var conn = new SqlConnection(stringConexao))
            {
                var            cmd = new SqlCommand(sql, conn);
                Models.Votacao p   = null;
                try
                {
                    conn.Open();
                    using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        while (reader.Read())
                        {
                            p       = new Models.Votacao();
                            p.Id    = (int)reader["id"];
                            p.Nome  = reader["Nome"].ToString();
                            p.Idade = (int)reader["Idade"];
                            p.Voto  = (int)reader["voto"];
                            lista.Add(p);
                        }
                    }
                }

                catch (Exception e)
                {
                    throw e;
                }
            }
            if (lista == null)
            {
                lista = new List <Models.Votacao>();
            }

            return(lista
                   .OrderBy(item => item.Id)
                   .ToList());
        }