Error adding data to the database

1

I'm having trouble inserting information with parameters:

private static void InsereNovoMenuParaOUsuario(int idAcao, DTO.ModulosProgramaAcoes acao)
{
    using (var conn =  Conexao.ConectaDb()) {
        var listUser = new List<DTO.ModulosMenuAcessoUser>();

        var cmd = new SqlCommand
        {
            Connection = conn,
            CommandType = CommandType.Text,
            CommandText = "SELECT DISTINCT idUser FROM ModulosMenuAcessoUser"
        };

        conn.Open();

        var adap = new SqlDataAdapter(cmd);
        var dt = new DataTable();
        adap.Fill(dt);


        for (var i = 0; i < dt.Rows.Count; i++)
        {
            var user = new DTO.ModulosMenuAcessoUser()
            {
                IdUser = Convert.ToInt32(dt.Rows[i]["idUser"]),
                IdModulo = acao.IdModulo,
                IdPrograma = acao.IdPrograma,
                IdAcao = idAcao
            };

            listUser.Add(user);
        }

        foreach (var acesso in listUser)
        {

            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "INSERT ModulosMenuAcessoUser(IdModulo,IdPrograma,IdAcoes,IdUser)" + Environment.NewLine +
                               "VALUES " + Environment.NewLine +
                               "(@IdModulo,@IdPrograma,@IdAcoes,@IdUser)";

            cmd.Parameters.Add("@IdUser", SqlDbType.Int).Value = acesso.IdUser;
            cmd.Parameters.Add("@IdModulo", SqlDbType.Int).Value = acesso.IdModulo;
            cmd.Parameters.Add("@IdPrograma", SqlDbType.Int).Value = acesso.IdPrograma;
            cmd.Parameters.Add("@IdAcoes", SqlDbType.Int).Value = acesso.IdAcao;

        }

        var transaction = conn.BeginTransaction();
        cmd.Transaction = transaction;

        try {
            cmd.ExecuteNonQuery();
            transaction.Commit();
        }
        catch (Exception e) {
            transaction.Rollback();
            throw e;
        }

    }
}

displays the following error:

  

e = {"The variable name '@IdUser' has already been declared.   variables must be unique in a batch of queries or in a   stored procedure. "}

    
asked by anonymous 14.08.2018 / 03:03

0 answers