[英]Unable to read connection string from Config File
我的项目中有一个app.config文件,如下所示。
我有以下代码来读取连接字符串:
string connectionstring = ConfigurationManager.ConnectionStrings["LibraryReservationSystemEntities"].ConnectionString;
它显示异常,如下所示。
你调用的对象是空的。
我们该如何纠正?
注意:这是一个类库项目。 我从另一个具有EF的EMDX文件的项目中复制了此连接字符串。 我当前的解决方案中只有一个项目。
注意:我需要从我的项目中实例化(EF)的ObjectContext 。 EMDX在其他项目中可用。
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="LibraryReservationSystemEntities" connectionString="metadata=res://*/MyEDMtest.csdl|res://*/MyEDMtest.ssdl|res://*/MyEDMtest.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.;AttachDbFilename=C:\DevTEST\Databases\LibraryReservationSystem.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
参考
您不能有库项目的配置文件 。 此配置文件与执行的程序集相关,该程序集可以是Winform应用程序,WPF应用程序,控制台应用程序,IIS中的ASP.Net网站...
在执行的实际程序集的app.config(或web.config)文件中添加ConnectionStrings
部分。
检查一下
you need to add a .dll reference for configuration manager
recheck if your connection string is right
check if you have more than one configuration file ex. web.config and app.config; so the ConfigurationManager is referencing the wrong file in the solution.
如果ConnectionStrings [“ myConnection”]返回null,则在构造函数中对其进行解引用以获取Name属性将失败。 那肯定不是错误所在吗?
为什么不在该行上放置断点,然后查看ConfigurationManager.ConnectionStrings以检查其认为的内容-并非常仔细地检查输入错误。
之后,在该方法的第一行上放置一个断点,并检查connectionString的值是什么。 将null传递给SqlConnection构造函数实际上并不会引发异常,但是在尝试打开它时会收到InvalidOperationException。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.