Error trying to open SQL connection - Server Version - System.Invalidoperationexception - Connection is closed

Asked

Viewed 351 times

0

Hello.

When trying to open a connection using the class SqlConnection of lib SqlClient my class conexao - formerly null - is as follows:

inserir a descrição da imagem aqui inserir a descrição da imagem aqui

That class conexao is the type SqlConnection and receives the return of my static function ConexaoBd.GetConexao()

using System.Data.SqlClient;
using System.Text;

namespace core.Util
{
    public class ConexaoBd
    {
        public static SqlConnection GetConexao()
        {
            StringBuilder connectionString = new StringBuilder();
            connectionString.Append("Data Source=DESKTOP-IUVDEOS;");
            connectionString.Append(" ");
            connectionString.Append("Initial Catalog=ECommerceGames;");
            connectionString.Append(" ");
            connectionString.Append("Integrated Security=true;");
            return new SqlConnection(connectionString.ToString());
        }
    }
}

The curious thing is that I can connect to my base via SQL Management Studio and via SQL Server Explorer from Visual Studio normally.

I tried connecting with the connection string of SQL Server Explorer uses, but also could not.

I’ve tried the following connection string variations:

"Data Source=DESKTOP-IUVDEOS; Initial Catalog=Ecommercegames; Integrated Security=true;"

"Data Source=DESKTOP-IUVDEOS; Initial Catalog=Ecommercegames; Integrated Security=SSPI;"

"Data Source=DESKTOP-IUVDEOS SQLEXPRESS; Initial Catalog=Ecommercegames; Integrated Security=true;" "Data Source=DESKTOP-IUVDEOS SQLEXPRESS; Initial Catalog=Ecommercegames; Integrated Security=SSPI;"

"Data Source=DESKTOP-IUVDEOS,1433; Initial Catalog=Ecommercegames; Integrated Security=true;"

"Data Source=DESKTOP-IUVDEOS,1433; Initial Catalog=Ecommercegames; Integrated Security=SSPI;"

I tried to connect as Firewall disabled too, but without success. The SQL Server service is running automatically.

Obs: no connection string in my appsettings.json.

Use Visual Studio 2019 with ASP.NET Core 2.2 and SQL Server 2017 Express v14.1805.4072.1

I appreciate any guidance.

Edited - I just performed more tests and nothing worked.

using core.Util;
using System;
using System.Collections.ObjectModel;
using System.Data.SqlClient;

namespace Testes
{
    public class TesteConexao
    {
        public static void TestarConexao()
        {
            Collection<string> stringsConexao = new Collection<string>();
            stringsConexao.Add("Data Source=DESKTOP-IUVDEOS; Initial Catalog=ECommerceGames; Integrated Security=true;");
            stringsConexao.Add("Server=DESKTOP-IUVDEOS; Database=ECommerceGames;Trusted_Connection=True;");
            stringsConexao.Add("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=master;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
            foreach (var item in stringsConexao)
            {
                SqlConnection conexao = ConexaoBd.GetConexaoTeste(item);
                Console.WriteLine("String de conexão: " + conexao.ConnectionString);
                Console.WriteLine("Estado da conexão: " + conexao.State);
            }
            Console.ReadLine();
        }
    }
}

Exit from testing:

inserir a descrição da imagem aqui

I am conducting the opening of connection and consultation as follows:

using System;
using System.Data.SqlClient;
using dominio;
using dominio.Jogo;

namespace core.Impl.Dao.Jogo
{
    public class ProdutoDAO : AbstractDAO
    {
        public ProdutoDAO():base("Produtos", "ProdutoId")
        {
        }

        public override void Salvar(EntidadeDominio entidade)
        {
            Produto produto = (Produto) entidade;
            string cmdTextoProduto;
            string cmdTextoGenero;
            string cmdTextoPais;

            cmdTextoProduto = "INSERT INTO Produtos(Titulo," +
                                                   "Desenvolvedora," +
                                                   "ClassificacaoEtaria," + 
                                                   "DataLancamento," + 
                                                   "TamanhoEmDisco," + 
                                                   "Sinopse," + 
                                                   "RequisitosMinimos," +
                                                   "GrupoPrecificacao," +
                                                   "Status," +
                                                   "DataCadastro" +
                              ") " +
                              "VALUES(@Titulo," +
                                     "@Desenvolvedora" +
                                     "@ClassificacaoEtaria," +
                                     "@DataLancamento," +
                                     "TamanhoEmDisco," +
                                     "@Sinopse," +
                                     "@RequisitosMinimos," +
                                     "@GrupoPrecificacao," +
                                     "@Status," +
                                     "@DataCadastro" +
                              ")";
            SqlCommand comandoProduto = new SqlCommand(cmdTextoProduto);
            comandoProduto.Parameters.AddWithValue("@Titulo", produto.Titulo);
            comandoProduto.Parameters.AddWithValue("@Desenvolvedora", produto.Desenvolvedora);
            comandoProduto.Parameters.AddWithValue("@ClassificacaoEtaria", produto.ClassificacaoEtaria);
            comandoProduto.Parameters.AddWithValue("@DataLancamento", produto.DataLancamento);
            comandoProduto.Parameters.AddWithValue("@TamanhoEmDisco", produto.TamanhoEmDisco);
            comandoProduto.Parameters.AddWithValue("@Sinopse", produto.Sinopse);
            comandoProduto.Parameters.AddWithValue("@RequisitosMinimos", produto.RequisitosMinimos);
            comandoProduto.Parameters.AddWithValue("@GrupoPrecificacao", produto.GrupoPrecificacao);
            comandoProduto.Parameters.AddWithValue("@Status", produto.Status);
            comandoProduto.Parameters.AddWithValue("@DataCadastro", produto.DataCadastro);

            cmdTextoGenero = "INSERT INTO ProdutosGeneros(ProdutoId," +
                                                         "GeneroId," +
                             ") " +
                             "VALUES(@ProdutoId," +
                                    "@GeneroId" +
                             ")";
            SqlCommand comandoGenero = new SqlCommand(cmdTextoGenero);

            cmdTextoPais = "INSERT INTO ProdutosPaises(ProdutoId," +
                                                        "PaisId," +
                           ") " +
                           "VALUES(@ProdutoId," +
                                  "@PaisId" +
                           ")";
            SqlCommand comandoPais = new SqlCommand(cmdTextoPais);

            try
            {
                Conectar();
                BeginTransaction();
                int a = comandoProduto.ExecuteNonQuery();
                foreach (var item in produto.Generos)
                {
                    comandoGenero.Parameters.AddWithValue("@ProdutoId", produto.Id);
                    comandoGenero.Parameters.AddWithValue("@GeneroId", item);
                    int b = comandoGenero.ExecuteNonQuery();
                }
                foreach (var item in produto.PaisesProibicao)
                {
                    comandoPais.Parameters.AddWithValue("@ProdutoId", produto.Id);
                    comandoPais.Parameters.AddWithValue("@Pais", item);
                    int c = comandoPais.ExecuteNonQuery();
                }
                Commit();
            }
            catch (SqlException e)
            {
                Rollback();
                throw e;
            }
            catch (InvalidOperationException e)
            {
                throw e;
            }
            finally
            {
                comandoProduto.Dispose();
                comandoGenero.Dispose();
                comandoPais.Dispose();
                Desconectar();
            }
        }
    }
}

The class below has Open and close connections and transactions methods:

using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using core.Util;
using dominio;

namespace core.Impl.Dao
{
    public abstract class AbstractDAO : IDAO
    {
        protected SqlConnection conexao;
        protected string tabela;
        protected string idTabela;
        private DbTransaction transacao;

        public AbstractDAO(SqlConnection conexao, string tabela, string idTabela)
        {
            this.tabela = tabela;
            this.idTabela = idTabela;
            this.conexao = conexao;
        }

        protected AbstractDAO(string tabela, string idTabela)
        {
            this.tabela = tabela;
            this.idTabela = idTabela;
        }

        public virtual void Salvar(EntidadeDominio entidade)
        {
            throw new NotImplementedException();
        }

        public virtual void Alterar(EntidadeDominio entidade)
        {
            throw new NotImplementedException();
        }

        public virtual List<EntidadeDominio> Consultar(EntidadeDominio entidade)
        {
            throw new NotImplementedException();
        }

        public void Excluir(EntidadeDominio entidade)
        {
            string cmdTexto = "DELETE FROM '" + tabela + "' WHERE ProdutoId = '" + idTabela + "'";
            SqlCommand comando = new SqlCommand(cmdTexto);
            try
            {
                Conectar();
                comando.ExecuteNonQuery();
                Commit();
            }
            catch (DbException e)
            {
                Rollback();
                throw e;
            }
            finally
            {
                Desconectar();
                comando.Dispose();
            }
        }

        protected void Conectar()
        {
            try
            {
                if (conexao == null)
                    conexao = ConexaoBd.GetConexao();
            }
            catch (SqlException e)
            {
                throw e;
            }
            catch (InvalidOperationException e)
            {
                throw e;
            }
        }

        protected void Desconectar()
        {
            if (conexao != null)
            {
                conexao.Close();
                conexao.Dispose();
            }
        }

        public void BeginTransaction()
        {
            try
            {
                transacao = conexao.BeginTransaction();   
            }
            catch (DbException e)
            {
                throw e;
            }
        }

        public void Commit()
        {
            try
            {
                transacao.Commit();
            }
            catch (DbException e)
            {
                throw e;
            }
        }

        public void Rollback()
        {
            try
            {
                transacao.Rollback();
            }
            catch (DbException e)
            {
                throw e;
            }
        }
    }
}

The order to open and close connection I be based on this video.

  • Try with string connection indicating the instance, thus: "Data Source=.\SQLExpress; Initial Catalog=ECommerceGames; Integrated Security=SSPI;"

1 answer

0


friend, try replacing your Getconexao method with a simpler one, for example

 public static SqlConnection GetConexao(){

    return new 
     SqlConnection("
         Server=DESKTOP-IUVDEOS;Database=ECommerceGames;Trusted_Connection=True;"
     );
    }

also recommend the site https://www.connectionstrings.com/sql-server/ to help you search for future connection string.

I hope I’ve helped in some way...

[UPDATED]

After a few messages exchanged, I discovered that the problem was the missing code snippet Open.(); in the way Connect.

  • Did not roll. Same error occurred.

  • I am making a test here tbm, actually occurred the same error...

  • friend, I made here a mini test to make the connection and then use this connection to perform a query in the database, even with the error I was able to perform a select and the same returned me the desired data

  • follow the test link: https://imgur.com/rjYQdIF

  • In my case, it is an Insert. I checked in the bank and it does not persist. I just included some tests I asked in the question.

  • friend you are sure you are opening the connection before trying to perform an sql command? because I realized an Insert, in the same example that I posted with the link, and it’s working normal, the error that gives me seems, because I did not go after searching, occurs when you do not open the connection, you just instantiate a connection but does not open it...

  • I performed a quick search on this exception, see the link: https://stackoverflow.com/questions/33282511/how-to-fix-serverversion-threw-an-exception-type-system-invalidoperatione and it seems that in fact this exception occurs when vc does not open the connection, as I had said in the previous comment...

  • So I’m opening, but I’m not sure if it’s the best opening order. I included more details in the question.

  • 1

    in the Connect method, after you call the Getconnectionwith, put the following line: connection. Open(); *You will have to put the if keys, see if it goes...

  • That was it man. Wow like I didn’t see? Thank you so much for the help!

  • Yeah, you were just instantiating a connection but you weren’t opening it... it happens, I’m happy to help... if you can, choose my answer as right to close the question as answered...hug

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.