如果这可以帮助其他人,这里是我创建的读取里面T4实体框架的连接字符串的一个片段。您将模型名称(也是连接字符串的名称)传递给它。它发现并解析我需要的连接位。当它不成功时它也会引发有用的错误。
要使用:
A.在模板的顶部粘贴此,如果您还没有引用这些组件:
<#@ assembly name="EnvDTE" #>
<#@ assembly name="System.Configuration" #>
B.在您的模板结束这个丑陋的(但紧凑)的代码粘贴:
<#+
string GetEFConnectionString(string modelName)
{
string file = null, key = "provider connection string=\"";
foreach (EnvDTE.ProjectItem item in ((EnvDTE.Project)((Array)((EnvDTE.DTE)((IServiceProvider)this.Host).GetService(typeof(EnvDTE.DTE))).ActiveSolutionProjects).GetValue(0)).ProjectItems)
if (System.Text.RegularExpressions.Regex.IsMatch(item.Name, "(app|web).config", System.Text.RegularExpressions.RegexOptions.IgnoreCase)) {
file = item.get_FileNames(0); break;
}
if (file == null) throw new Exception("config file could not be found");
var config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(new System.Configuration.ExeConfigurationFileMap() { ExeConfigFilename = file }, System.Configuration.ConfigurationUserLevel.None);
var cn = config.ConnectionStrings.ConnectionStrings[modelName];
if (cn == null) throw new Exception(modelName + " connection string could not be found");
string s = cn.ConnectionString;
int pos = s.IndexOf(key,StringComparison.OrdinalIgnoreCase);
if (pos<0) throw new Exception("could not find value '" + key + "' inside connection string");
pos += key.Length;
int pos2=s.IndexOf('"',pos);
if (pos2 < 0) throw new Exception("could not find ending \" in connection string");
return s.Substring(pos,pos2-pos);
}
#>
下使用它像这样:
using(var connection = new SqlConnection(GetEFConnectionString("Database"))) {
..
}
,我相信这是正确的。但是我还没有足够的智慧来弄清楚如何获得EF连接字符串。我已经在模板中的调试器中检查了所有可以找到的所有内容,试图找到没有成功的文档,并查看了RC附带的模板。我要么是盲目的,要么是什么。你有获得EF连接字符串的提示吗? – 2010-02-19 16:25:06
我会更新答案。 – 2010-02-19 16:31:18
这似乎是正确的方法,所以我正在对它进行评估。但是,我仍然陷入困境,目前还不得不从事其他一些工作。当前正在运行的应用程序是devenv.exe,所以我没有运行到该项目的app.config。链接必须存在,所以我会在以后继续探索。 – 2010-02-19 18:23:19