SqlConnection 错误 "Object reference not set to an instance of an object."

Error "Object reference not set to an instance of an object." for SqlConnection

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["TropicalConnectionString"].ConnectionString);  

它说

Object reference not set to an instance of an object.

为了检查错误,我给出了我的 app.config,我想知道我是否为 Initial Catalog 等提供了错误的名称?

这是我的 app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="TropicalConnectionString" 
             connectionString="Data Source = JIRAN-PC; Initial Catalog = TropicalServer; Integrated Security = True"
             providerName="System.Data.SqlClient" />
        <add name="TropicalServiceWinApp.Properties.Settings.TropicalConnectionString"
             connectionString="Data Source=JIRAN-PC;Initial Catalog=TropicalServer;Integrated Security=True"
             providerName="System.Data.SqlClient" />
    </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_ITropicalService" />
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:5483/TropicalService.svc"
                binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_ITropicalService"
                contract="TropicalServiceRef.ITropicalService" name="BasicHttpBinding_ITropicalService" />
        </client>
    </system.serviceModel>
</configuration>

试试这个:

  1. Select 解决方案资源管理器中的 App.Config 文件
  2. 在 属性 window select 复制到输出目录以始终复制。
  3. 现在构建应用程序并重试。