Error when connecting to Sqlserver C# Web.config database

Asked

Viewed 337 times

2

I’m trying to make an application .NET MVC, but when I connect to the bank is giving the following error:

An Exception of type 'System.Nullreferenceexception' occurred in Gerarxml.dll but was not handled in user code Additional information: Object reference not defined for an instance of an object.

My Web.config is with all the right paths, look how is the string connected

add name="EfDbContext" connectionString="Data Source=192.168.230.14;Initial Catalog=db_nfe;User ID=**;Password=******" providerName="System.Data.SqlClient"

And mine controller is like this

public SqlConnection sqlConn = 
    new SqlConnection(ConfigurationManager
                       .ConnectionStrings["connectionStrings"]
                         .ConnectionString);

And the only way the bank uses it is like this

private string ConsultaChaveXML(string chaves)
{
    sqlConn.Open();
    string sql = $@"SELECT * FROM db_nfe..nota_fiscal_empresa
            WHERE chave_acesso = '{chaves}'";

    SqlCommand selectChave = new SqlCommand(sql);
    //Campo do xml = dsc_xml_nota_fiscal
    SqlDataReader retornoSelect = selectChave.ExecuteReader();

    return retornoSelect["dsc_xml_nota_fiscal"].ToString();
}
private XDocument CriarXML(string xml, string chave)
{
    var xmlFile = new XDocument("root", xml);
    return xmlFile;
}
  • I guess you didn’t pass the connection to the SqlCommand?

  • I just did that and it didn’t work out

  • Which line gives the error?

  • public Sqlconnection sqlConn = new Sqlconnection(Configurationmanager.Connectionstrings["connectionStrings"]. Connectionstring);

  • The error: System.Nullreferenceexception was unhandled by user code Hresult=-2147467261 Message=Undefined object reference for an instance of an object. Source=Gerarxml Stacktrace: in Gerarxml.Controllers.Homecontroller.. ctor() na c: users Filipe.silva Documents visual studio 2015 Projects Gerarxml Gerarxml Controllers Homecontroller.Cs:line 17 Innerexception:

  • This generating methodXML is this private Xdocument Criaxml(string xml, key string) { var xmlFile = new Xdocument("root", xml); Return xmlFile; }

  • look at .ConnectionStrings["connectionStrings"] shouldn’t be .ConnectionStrings["EfDbContext"]?

  • 1

    That msm man, can you put that in the answer? Vc is Top, vlw

Show 3 more comments

1 answer

1


Your ConnectionString has the name of the key wrong:

change:

public SqlConnection sqlConn = 
    new SqlConnection(ConfigurationManager
                       .ConnectionStrings["connectionStrings"]
                         .ConnectionString);

therefore:

public SqlConnection sqlConn = 
    new SqlConnection(ConfigurationManager
                       .ConnectionStrings["EfDbContext"]
                         .ConnectionString);

Browser other questions tagged

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