从另一个文件加载数据库连接字符串

时间:2014-07-14 17:20:33

标签: c#

我有一个Web应用程序,它有一个Web.config文件,但我需要它从另一个配置文件加载几个部分,这些部分位于一个定义的位置(不是我的设计!)。其中一个部分是connectionStrings。我已经尝试了以下操作,但是当我的Web服务加载说System.InvalidOperationException时,我收到错误:没有名为' MyDataModel'的连接字符串。可以在应用程序配置文件中找到。

ConfigurationFileMap map = new ConfigurationFileMap(@"C:\conf1.conf");
config = ConfigurationManager.OpenMappedMachineConfiguration(map);

ConfigurationManager.RefreshSection("connectionStrings");

以下是我的配置文件的相关部分:

    <configSections>
    <section name="connectionStrings" type="System.Configuration.ConnectionStringsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" requirePermission="false"/>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="MyDataModel" providerName="MySql.Data.MySqlClient" connectionString="server=localhost;
      ..."/>
  </connectionStrings>

我知道我可以&#34;包括&#34;另一个配置文件中的配置文件片段,但在此处不起作用,因为将包含的文件包含其他几个部分。有没有办法可以让运行时正确加载我的外部配置文件?谢谢!

1 个答案:

答案 0 :(得分:1)

使用ConfigurationManager读取映射配置是正确的。接下来的一点是,您需要手动抓取密钥。这是一个非常相似的问题,答案解决了你想要的东西的手动阅读:

Equivalent to 'app.config' for a library (DLL)

从以上链接复制:

string GetAppSetting(Configuration config, string key)
{
    KeyValueConfigurationElement element = config.AppSettings.Settings[key];
    if (element != null)
    {
        string value = element.Value;
        if (!string.IsNullOrEmpty(value))
            return value;
    }
    return string.Empty;
}

编辑:

由于EF只查看本地配置(AFAIK),那么使用T4模板生成web.config呢?然后,您可以从远程配置文件中输入必要的数据。我发现了一篇关于如何做到这一点的好文章:

http://www.geoffhudik.com/tech/2010/10/19/webconfig-automation-with-t4-and-a-macro.html

EDIT2:

在EF连接字符串中使用元数据是一种选择吗?如果是这样,您可以将其指向其他程序集而不必使用ConfigurationManager:

http://msdn.microsoft.com/en-us/library/vstudio/cc716756(v=vs.100).aspx