源起于想通过配置文件切换数据库为 MySql/Sql Server
但是使用EF4.0 的DataBase First模式下,选择【根据模型生成数据库】时,会覆盖掉自己写的自定义代码(VS2010 为 edmx文件名.Designer.cs;VS2012为 edmx文件名.Context.cs文件)。
故想通过修改T4模板来修改 数据库上下文文件的生成,可以自动生成我想要的代码。
开始走了弯路,想在T4中读取好项目文件下 App.config的配置信息;后面发现这样要提供两个dll供生产环境切换,所以发现有更简单的办法,自己想复杂了,呵呵。
以下以 VS2012 的 edmx文件名.Context.tt文件 为例
VS2010 木有 使用T4模板文件,它 使用了自定义工具EntityModelCodeGenerator生成的,不过也可以通过自己新建T4模板文件实现和VS2012同样的效果。
1、
类库项目下的配置文件:
2、修改 edmx文件名.Context.tt T4模板文件。
2.1 首先文件头部添加引用
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。
3、修改 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