如果這可以幫助其他人,這裏是我創建的讀取裏面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