如何从库中访问连接字符串 [英] How to access a connection string from within a library

查看:47
本文介绍了如何从库中访问连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在单独的类库项目中有一个Web项目(mvc)和数据访问层.我需要访问该库项目中位于app.config中的连接字符串.

I have a web project (mvc) and data access layer in a separated class library project. I need to access to a connection string in app.config which sits in that library project.

ConfigurationManager.ConnectionStrings [0] .ConnectionString拉出一些奇怪的东西.库的配置和Web项目的配置文件中都没有这种设置.

ConfigurationManager.ConnectionStrings[0].ConnectionString pulls something strange. I don't have this kind of settings neither in the library's config nor in the web project's config files.

App.config看起来像这样:

the App.config looks like that:

<?xml version="1.0" encoding="utf-8" ?>
 <configuration>
  <connectionStrings>
   <add name="DALConnectionString" connectionString="User ID=sa;Password=pass;Initial     Catalog=db;Data Source=srv\SQL2005;" />
 </connectionStrings>
</configuration>

推荐答案

默认情况下,类库无法访问配置文件.

By default, a class library can't access a config file.

类库的客户端(在本例中为您的Web项目)可以提供配置设置.

The client of the class library, in this case your web project, can provide config settings.

因此,将所有相关设置(连接字符串)放入Web的配置文件中.类库中的ConfigurationManager代码将使用Web项目的配置设置.

Therefore, put all the relevant settings, the connection strings, in the web's config file. The ConfigurationManager code in the class library will use the web projects config settings.

这篇关于如何从库中访问连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆