T4模板讀取項目Web.config/App.config文件下的AppSetting或ConnectionStrings

源起於想經過配置文件切換數據庫爲 MySql/Sql Server數據庫

可是使用EF4.0 的DataBase First模式下,選擇【根據模型生成數據庫】時,會覆蓋掉本身寫的自定義代碼(VS2010 爲 edmx文件名.Designer.cs;VS2012爲 edmx文件名.Context.cs文件)。app

故想經過修改T4模板來修改 數據庫上下文文件的生成,能夠自動生成我想要的代碼。工具

開始走了彎路,想在T4中讀取好項目文件下 App.config的配置信息;後面發現這樣要提供兩個dll供生產環境切換,因此發現有更簡單的辦法,本身想複雜了,呵呵。網站

 

如下以 VS2012 的 edmx文件名.Context.tt文件 爲例spa

VS2010 木有 使用T4模板文件,它 使用了自定義工具EntityModelCodeGenerator生成的,不過也能夠經過本身新建T4模板文件實現和VS2012一樣的效果。code

 

一、blog

類庫項目下的配置文件:字符串

 

二、修改  edmx文件名.Context.tt T4模板文件。get

    2.1 首先文件頭部添加引用string

1 <#@ assembly name="System.Configuration.dll" #>
2 <#@ import namespace="System.Configuration" #>

 

   2.2 增長讀取Config配置代碼塊

//獲取解決方案的config配置
string appPath = Path.Combine(Host.ResolveAssemblyReference("$(SolutionDir)"), "項目名稱","App.config");

//獲取項目下的config配置
string appPath = Path.Combine(Host.ResolveAssemblyReference("$(ProjectDir)"),"App.config");
var configMap = new ExeConfigurationFileMap { ExeConfigFilename = appPath }; 
Configuration econfig = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
//獲取connectionStrings 節點
//ConnectionStringsSection connSection = (ConnectionStringsSection)config.GetSection("connectionStrings");

//獲取appSettings 節點
AppSettingsSection appSettingSection = (AppSettingsSection)econfig.GetSection("appSettings");
var DbType = appSettingSection.Settings["DbType"] == null?"" : appSettingSection.Settings["DbType"].Value;
string ConnStr = string.Concat("name=" , DbType, "<#=container.Name#>");

 

     2.3 修改傳入連接字符串name信息

           修改前:   public <#=code.Escape(container)#>() : base("name=<#=container.Name#>")

           修改後:   public <#=code.Escape(container)#>() : base("<#=ConnStr#>")

 

      2.4 保存文件,便可看到相應文件下  edmx文件名.Context.cs文件 以下,傳入了 MySql數據庫的配置串的name

           

 

---------------------------------分割線------------------------------------

簡單的解決辦法 相信你們想到了

直接生成代碼到 edmx文件名.Context.cs文件 中 讀取config配置,這樣就不用生成多個dll,直接獲取網站下的相應配置就OK。

三、修改  edmx文件名.Context.tt T4模板文件。

      修改前: public <#=code.Escape(container)#>() : base("name=<#=container.Name#>")

      修改後:

      

private static string DbType = System.Configuration.ConfigurationManager.AppSettings["DbType"] == null ? "" 
                                 : System.Configuration.ConfigurationManager.AppSettings["DbType"].ToString();
    private static string ConnStr = string.Concat("name=", DbType , "<#=container.Name#>");

    public <#=code.Escape(container)#>()
        : base(ConnStr)

 

 

 保存文件,OK生成的 edmx文件名.Context.cs文件 就有讀取配置的代碼了,之後不再擔憂代碼被覆蓋了,以下:

 

 

總結,之前對T4 很模糊,雖然就改動了這麼一點點的東西,可是仍是挺高興的,哈哈。

 

 T4模板 and EF 的連接: https://msdn.microsoft.com/en-us/data/gg558520.aspx

 

https://msdn.microsoft.com/en-us/library/cc982041.aspx

 

https://msdn.microsoft.com/en-us/library/dd456821.aspx

相關文章
相關標籤/搜索