public NivelUsuarioModel RecuperarPeloId(int id)
        {
            NivelUsuarioModel ret = null;

            Connection();

            using (SqlCommand command = new SqlCommand(" SELECT *            " +
                                                       "   FROM NivelUsuario " +
                                                       "  WHERE Id=@Id       ", con))
            {
                con.Open();

                command.Parameters.AddWithValue("@Id", SqlDbType.Int).Value = id;

                var reader = command.ExecuteReader();

                if (reader.Read())
                {
                    ret = new NivelUsuarioModel()
                    {
                        Id     = (int)reader["Id"],
                        Codigo = (string)reader["Codigo"],
                        Nome   = (string)reader["Nome"],
                        Ativo  = (bool)reader["Ativo"]
                    };
                }
            }
            return(ret);
        }
        public JsonResult SalvarNivelUsuario(NivelUsuarioModel nivelUsuarioModel, List <int> idUsuarios)
        {
            var resultado = "OK";
            var mensagens = new List <string>();
            var idSalvo   = string.Empty;

            if (!ModelState.IsValid)
            {
                resultado = "AVISO";
                mensagens = ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToList();
            }
            else
            {
                nivelUsuarioModel.Usuarios = new List <UsuarioModel>();


                foreach (var id in idUsuarios)
                {
                    nivelUsuarioModel.Usuarios.Add(new UsuarioModel()
                    {
                        Id = id
                    });
                }
                try
                {
                    nivelUsuarioRepositorio = new NivelUsuarioRepositorio();

                    var id = nivelUsuarioRepositorio.Salvar(nivelUsuarioModel);

                    if (id > 0)
                    {
                        idSalvo = id.ToString();
                    }
                    else
                    {
                        resultado = "ERRO";
                    }
                }catch (Exception ex)
                {
                    resultado = "ERRO";
                    throw new Exception(ex.Source);
                }
            }

            return(Json(new { Resultado = resultado, Mensagens = mensagens, IdSalvo = idSalvo }));
        }
        public int Salvar(NivelUsuarioModel nivelUsuarioModel)
        {
            var ret = 0;

            var model = RecuperarPeloId(nivelUsuarioModel.Id);

            if (model == null)
            {
                Connection();

                using (SqlCommand command = new SqlCommand("INSERT INTO NivelUsuario ( Codigo,    " +
                                                           "                           Nome,      " +
                                                           "                           Ativo      " +
                                                           "                         )            " +
                                                           "                  VALUES ( @Codigo,   " +
                                                           "                           @Nome,     " +
                                                           "                           @Ativo     " +
                                                           "                         );           " +
                                                           " select convert(int, scope_identity()) ", con))
                {
                    con.Open();

                    command.Parameters.AddWithValue("@Codigo", SqlDbType.VarChar).Value = nivelUsuarioModel.Codigo;
                    command.Parameters.AddWithValue("@Nome", SqlDbType.VarChar).Value   = nivelUsuarioModel.Nome;
                    command.Parameters.AddWithValue("@Ativo", SqlDbType.Int).Value      = nivelUsuarioModel.Ativo;

                    nivelUsuarioModel.Id = (int)command.ExecuteScalar();

                    ret = nivelUsuarioModel.Id;
                }
            }
            else
            {
                Connection();


                using (SqlCommand command = new SqlCommand(" UPDATE NivelUsuario    " +
                                                           "    SET Codigo=@Codigo, " +
                                                           "        Nome=@Nome,     " +
                                                           "        Ativo=@Ativo    " +
                                                           "  WHERE Id=@Id          ", con))
                {
                    con.Open();

                    command.Parameters.AddWithValue("@Codigo", SqlDbType.VarChar).Value = nivelUsuarioModel.Codigo;
                    command.Parameters.AddWithValue("@Nome", SqlDbType.VarChar).Value   = nivelUsuarioModel.Nome;
                    command.Parameters.AddWithValue("@Ativo", SqlDbType.Int).Value      = nivelUsuarioModel.Ativo;
                    command.Parameters.AddWithValue("@Id", SqlDbType.Int).Value         = nivelUsuarioModel.Id;

                    if (command.ExecuteNonQuery() > 0)
                    {
                        ret = nivelUsuarioModel.Id;
                    }
                }
            }

            if (nivelUsuarioModel.Usuarios != null && nivelUsuarioModel.Usuarios.Count > 0)
            {
                Connection();

                using (SqlCommand commandExclusaoNivelUsuario = new SqlCommand(" DELETE Nivel_Usuario               " +
                                                                               "  WHERE IdNivelUsuario = @IdNivelUsuario ", con))
                {
                    con.Open();

                    commandExclusaoNivelUsuario.Parameters.AddWithValue("@IdNivelUsuario", SqlDbType.Int).Value = nivelUsuarioModel.Id;

                    commandExclusaoNivelUsuario.ExecuteScalar();
                }

                foreach (var usuario in nivelUsuarioModel.Usuarios)
                {
                    Connection();
                    using (SqlCommand commandInclusaoNivelUsuario = new SqlCommand(" INSERT INTO Nivel_Usuario( IdNivelUsuario,  " +
                                                                                   "                            IdUsuario        " +
                                                                                   "                          )                  " +
                                                                                   "                   VALUES ( @IdNivelUsuario, " +
                                                                                   "                            @IdUsuario       " +
                                                                                   "                          )                  ", con))
                    {
                        con.Open();


                        commandInclusaoNivelUsuario.Parameters.AddWithValue("@IdNivelUsuario", SqlDbType.Int).Value = nivelUsuarioModel.Id;
                        commandInclusaoNivelUsuario.Parameters.AddWithValue("@IdUsuario", SqlDbType.Int).Value      = usuario.Id;

                        commandInclusaoNivelUsuario.ExecuteScalar();
                    }
                }
            }
            return(ret);
        }