.net 在控制台应用程序中获取连接字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6014227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get connection string in console application
提问by nvtthang
I've created an Console application project then add new App.conf file into my project. In my configuration file, I copied connection string that I've created by adding entity framework as below:
我创建了一个控制台应用程序项目,然后将新的 App.conf 文件添加到我的项目中。在我的配置文件中,我复制了我通过添加实体框架创建的连接字符串,如下所示:
<connectionStrings>
<add name="DBEntities" connectionString="metadata=res://*/DBModel.csdl|res://*/DBModel.ssdl|res://*/DBModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=MY-LAPTOP;Initial Catalog=TestDB;User ID=test;Password=123123;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
On the program.cs I want to using ConfigurationManager class to retain the connection string but always raise me errors.
在 program.cs 上,我想使用 ConfigurationManager 类来保留连接字符串,但总是会引发我的错误。
String connString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
Please suggest me solutions. Thanks in advance.
请给我建议解决方案。提前致谢。
回答by Kevin McKelvin
Your connection string is called DBEntities
您的连接字符串被称为 DBEntities
Use this line in your code instead:
在您的代码中使用此行:
String connString = ConfigurationManager.ConnectionStrings["DBEntities"].ConnectionString;
回答by jgauffin
This is only a guess since you didn't include the actual exception in your question:
这只是一个猜测,因为您没有在问题中包含实际异常:
Add a reference to System.Configurationto your project.
添加System.Configuration对项目的引用。
回答by Jacob
Also, your name-attribute's value is DBEntities, but you are trying to access ApplicationServicesin your code.
此外,您的 name-attribute 的值为DBEntities,但您正试图ApplicationServices在您的代码中访问。

