2

I'm trying to make this simple call:

DataContext dc = new DataContext(ConfigurationManager.ConnectionStrings["MyDB"].ConnectionString)

And here's my app.config file:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="MyDB" connectionString="Server=STEVEN-PC;Database=MyDB;Trusted_Connection=yes;" />
  </connectionStrings>
</configuration>

But I'm getting an error: Object reference not set to an instance of an object.

It can't find the connection string. What am I doing wrong?

Steven
  • 18,761
  • 70
  • 194
  • 296
  • Sure your app.config is in the same path as the executable? –  May 16 '11 at 01:30
  • @Inuyasha - I have a Visual Studio solution with several projects. The app.config and the file I'm making the call from are in the same project. – Steven May 16 '11 at 01:32
  • I always like to confirm my assumptions by doing things like separating the call to the app.config from the instantiating the dataContext. Just to make sure that is where I'm failing. You're probably right, but every now and then it reveals something unexpected. – Richard Brightwell May 16 '11 at 01:36
  • 2
    You mention there are several projects. Is the one with the app.config your startup project? If not, you'll have to add your connection string to an app.config in the startup project. – Pete M May 16 '11 at 01:44

3 Answers3

15

A common mistake is trying to read a connection string from an app.config from a referenced project instead of from the executable project (the web site or .exe project). You may need to copy the config settings containing the connection string to your main config file.

Jacob
  • 77,566
  • 24
  • 149
  • 228
1

Double check the existence and contents of your configuration file in the build directory. That code should work fine if the config file is in place.

You could also pull put the connection string into a local variable so you can be sure the null reference exception is happening where you think it is.

Josh
  • 68,005
  • 14
  • 144
  • 156
0

You might need to specify the providerName:

<add name="MyDB" connectionString="Server=STEVEN-PC;Database=MyDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient" />
Brandon Montgomery
  • 6,924
  • 3
  • 48
  • 71
  • That's not necessary and even if it were specified, his code isn't accessing that property. – Josh May 16 '11 at 01:48