How to make connection strings available in a T4 template?

后端 未结 3 2192
有刺的猬
有刺的猬 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:40

    If anyone needs to resolve absolute path to a Web.config file (because e.g. a .tt file is included and used from multiple other .tt files in different relative paths):

    <#@ template debug="true" hostspecific="true" language="C#" #>
    <#@ assembly name="EnvDTE" #>
    <#@ Assembly Name="System.Configuration" #>
    <#@ import namespace="System.IO" #>
    <#@ import namespace="System.Configuration" #>
    <#+
    string GetConnectionString()
    {
        var map = new ExeConfigurationFileMap();
        var configPath = Path.Combine(
            Host.ResolveAssemblyReference("$(SolutionDir)"), "WwwFolderInSolution", "Web.config");
    
        map.ExeConfigFilename = configPath;
    
        var config = ConfigurationManager.
            OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
    
        return config.ConnectionStrings.ConnectionStrings["MyConnectionString"].ConnectionString;
    }
    #>
    

提交回复
热议问题