How to make connection strings available in a T4 template?

后端 未结 3 2190
有刺的猬
有刺的猬 2021-02-13 22:19

I\'ve written a T4 template where I instantiate an EF context to read some data. The problem is that the context cannot see the connection string from the Web.config.

Ho

3条回答
  •  梦如初夏
    2021-02-13 22:35

    I accessed a connection string from App.config from T4 template in the following way:

    <#@ template debug="false" hostspecific="true" language="C#" #>
    
    ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap(this.Host.ResolvePath(@"..\ProjName\App.config"));
    configFileMap.ExeConfigFilename = this.Host.ResolvePath(@"..\ProjName\App.config");
    Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
    string connectionString = config.ConnectionStrings.ConnectionStrings[0].ConnectionString;
    

提交回复
热议问题