如果你正在运行在设计时T4(CustomTool:TextTemplatingFilePreprocessor),模板代码被作为VisualStudio的进程的一部分执行。 VisualStudio加载devenv.exe.config而不是你的项目配置(你可以通过AppDomain.CurrentDomain.SetupInformation.ConfigurationFile来检查)。
这就是为什么你会得到null ref异常 - 'localconnection'连接字符串不在devenv.exe.config中。
可以使用ConfigurationManager.OpenMappedExeConfiguration装载该项目的配置文件:
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Configuration" #>
<#@ import namespace="System.Configuration"#>
<#@ import namespace="System.IO" #>
<#
string configPath = Path.Combine(Host.ResolveAssemblyReference("$(ProjectDir)"), "App.config");
var configFileMap = new ExeConfigurationFileMap{ExeConfigFilename = configPath};
var config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);
string connectionString = config.ConnectionStrings.ConnectionStrings["localconnection"].ConnectionString;
WriteLine(connectionString);
#>
注意,它必须是为了使用主机解决您的项目文件夹hostspecific =“真”。
你会得到什么错误? – AlexP
可能是[如何使连接字符串可用在一个t4模板](http://stackoverflow.com/questions/25460348/how-to-make-connection-strings-available -in-a-t4-template) – AlexP
@AlexP对不起,需要很长时间才能回复。通过对tmp文件的研究,发现[]字符串被正确编译,但配置管理器没有在项目的App.config中看到连接字符串 - 所以返回“null”。通过遍历所有连接字符串,仅找到默认的machine.config连接字符串 - 不是控制台项目特定的连接字符串。 :((VS 2015)感谢您对此的任何指导(我已经在写这个问题之前应用了您的链接,但它没有工作:()。 –