1

I am getting a null reference exception when trying to connect to the database via ConnectionCtrings["MyDB"].connectionstring.

This is in a using statement and is the same code I've used in many other projects, but it keeps telling me null reference and I don't know why.

The connection string named is named correctly in the web.config which is in the same project so I wouldn't expect there to be permissions issues.

What have I missed?

Edit: I have seen the suggested answers, these are solved by putting the string in the Web.Config which is where the connection string is.

Code: ConnectionString in Web.config

<connectionStrings>
    <add name="MyDB" connectionString="Data Source=192....; Initial Catalog=ProjectDb; Integrated Security=false; User Id=user; Password=password;" providerName="System.Data.SqlClient" />
</connectionStrings>

Function to access DB

public static Company RetrieveCompany(int id)
{
    var cmp = new Company();
    try
    {
        using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString))
        {
            con.Open();
            using (var cmd = new SqlCommand("RetreiveEmailProc", con))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@companyId", id);

                SqlDataReader sdr = cmd.ExecuteReader();
                while (sdr.Read())
                { // code omitted }
            }           

        }
    }
    catch(Exception ex)
    {

    }

    return cmp;
}
2

1 Answer 1

1

I think it is related to you using ConfigurationManager instead of the WebConfigurationManager. It is possible your code resides in another folder with a different web.config and the ConfigurationManager can't handle that inheritance problem.

Sign up to request clarification or add additional context in comments.

13 Comments

Thanks for the suggestion, unfortunately it gave the same error using WebConfigurationManager.
Can you set a break point and see what is in ConfigurationManager.ConnectionStrings?
I have done - what am I looking for? When I hover over WebConfigurationManager I get count 2, which I would think is wrong, surely there should only be one?
Can you see the items in there? Is your connection in there? I guess the default connections from your machine.config are in there too.
Strange, it doesn't appear to have anything related to the connection string it's pointed at, which would explain the null exception, but not sure as to what's causing it.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.