连接字符串中无法识别的元素

时间:2017-11-12 12:37:15

标签: c#

无法找到连接字符串的错误:

我得到了这个例外:

  

System.Configuration.ConfigurationErrorsException:配置系统初始化失败---> System.Configuration.ConfigurationErrorsException:无法识别的元素。 (D:\ C#\ learncsharp \ Data access \ AsyncSQL \ AsyncSQL \ bin \ Debug \ AsyncSQL.exe.Config line 2)

这是我的代码:

string connectionString = null;
string MovieDBContext = null;

try
{
    MovieDBContext = ConfigurationManager.ConnectionStrings["MovieDBContext"].ConnectionString;
    connectionString = ConfigurationManager.ConnectionStrings["ProgrammingInCSharpConnection"].ConnectionString;
}
catch (Exception e)
{
    Console.WriteLine( e.ToString() );
}

App.config中:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="MovieDBContext"
             connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
             providerName="System.Data.SqlClient" />
        <add name="ProgrammingInCSharpConnection" 
             connectionString="Data Source=(localdb)\v11.0;Initial Catalog=ProgrammingInCSharp;"
             providerName="System.Data.SqlClient" />
    </connectionStrings>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
    </startup>
</configuration>

有什么问题?以及如何获取哪些元素错误的详细信息?

1 个答案:

答案 0 :(得分:0)

确保您已在 <configSections> 元素中定义了该部分。更改您的配置,如下所示,

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <configSections />
    <connectionStrings>
         <add name="MovieDBContext"
            connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Movies.mdf;Integrated Security=True"
            providerName="System.Data.SqlClient"
        />
         <add name="ProgrammingInCSharpConnection" 
              providerName="System.Data.SqlClient" 
              connectionString="Data Source=(localdb)\v11.0;Initial Catalog=ProgrammingInCSharp;"
        />
    </connectionStrings>
</configuration>