小型的企业站快速搭建--T4模板生成实体类3
1.在解决方案中添加一个类库,名称Model.主要是通过T4模板来生成自动封装属性
2.工具-》扩展管理器-》联机库 搜索T4 Editor
T4 Editor",选择第一项 "tangible T4 Editor 2.0 plus modeling tools for VS2010" 进行安装即可
如果搜索不到可以查看http://www.cnblogs.com/zxbzl/p/6109133.html 这里有下载地址
3.新建文本模板名称 Model,代码一会提供
4添加数据库操作引用,并要生成多个类,添加 Modelauto.ttinclude
在银河系的基础上进行了改写,首字大字,INT32改为INT
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <#@ template language="C#" debug="True" hostspecific="True" #> 2 <#@ output extension=".cs" #> 3 <#@ assembly name="System.Data" #> 4 <#@ assembly name="System.xml" #> 5 <#@ import namespace="System.Collections.Generic" #> 6 <#@ import namespace="System.Data.SqlClient" #> 7 <#@ import namespace="System.Data" #> 8 <#@ include file="ModelAuto.ttinclude"#> 9 <# var manager = new Manager(Host, GenerationEnvironment, true) { OutputPath = Path.GetDirectoryName(Host.TemplateFile)}; #> 10 <# 11 string connectionString = "data source=(local);initial catalog=super;user id=diamond;password=88888888;"; 12 SqlConnection conn = new SqlConnection(connectionString); 13 conn.Open(); 14 System.Data.DataTable schema = conn.GetSchema("TABLES"); 15 string selectQuery = "select * from @tableName"; 16 SqlCommand command = new SqlCommand(selectQuery,conn); 17 SqlDataAdapter ad = new SqlDataAdapter(command); 18 System.Data.DataSet ds = new DataSet(); 19 20 string propQuery = "SELECT 表名=sobj.name,字段名=scol.name,字段说明=sprop.[value] FROM syscolumns as scol inner join sys.sysobjects as sobj on scol.id=sobj.id and sobj.xtype='U' and sobj.name<>'dtproperties' left join sys.extended_properties as sprop on scol.id=sprop.major_id and scol.colid=sprop.minor_id where sobj.name='@tableName' and scol.name='@columnName'"; 21 SqlCommand command2 = new SqlCommand(propQuery,conn); 22 SqlDataAdapter ad2 = new SqlDataAdapter(command2); 23 System.Data.DataSet ds2 = new DataSet(); 24 #> 25 26 <# 27 foreach(System.Data.DataRow row in schema.Rows) 28 { #> 29 30 <# 31 manager.StartBlock(row["TABLE_NAME"].ToString().Substring(0,1).ToUpper()+row["TABLE_NAME"].ToString().Substring(1)+".cs"); 32 #> 33 using System; 34 namespace Model 35 { 36 public class <#= row["TABLE_NAME"].ToString().Substring(0,1).ToUpper()+row["TABLE_NAME"].ToString().Substring(1)#> 37 { <# 38 ds.Tables.Clear(); 39 command.CommandText = selectQuery.Replace("@tableName",row["TABLE_NAME"].ToString()); 40 ad.FillSchema(ds, SchemaType.Mapped, row["TABLE_NAME"].ToString()); 41 foreach (DataColumn dc in ds.Tables[0].Columns) 42 { #> 43 <# 44 ds2.Tables.Clear(); 45 command2.CommandText = propQuery.Replace("@tableName",row["TABLE_NAME"].ToString()); 46 command2.CommandText = command2.CommandText.Replace("@columnName",dc.ColumnName); 47 ad2.Fill(ds2); 48 #> 49 <# if(dc.DataType.Name=="Int32"){ #> 50 public int <#= dc.ColumnName.Substring(0,1).ToUpper()+dc.ColumnName.Substring(1)#> {get;set;} 51 <# } else {#> 52 public <#= dc.DataType.Name #> <#= dc.ColumnName.Substring(0,1).ToUpper()+dc.ColumnName.Substring(1)#> {get;set;} 53 <# } #> 54 <# } #> 55 } 56 } 57 58 <# manager.EndBlock(); #> 59 60 <# 61 } #> 62 63 <# 64 manager.Process(true); 65 #> 66 67 68 69 70 71 72 73 74 75 76
银河系的源文件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 <#@ assembly name="System.Core"#> 2 <#@ assembly name="EnvDTE"#> 3 <#@ import namespace="System.Collections.Generic"#> 4 <#@ import namespace="System.IO"#> 5 <#@ import namespace="System.Text"#> 6 <#@ import namespace="Microsoft.VisualStudio.TextTemplating"#> 7 8 <#+ 9 10 class Manager 11 { 12 public struct Block { 13 public String Name; 14 public int Start, Length; 15 } 16 17 public List<Block> blocks = new List<Block>(); 18 public Block currentBlock; 19 public Block footerBlock = new Block(); 20 public Block headerBlock = new Block(); 21 public ITextTemplatingEngineHost host; 22 public ManagementStrategy strategy; 23 public StringBuilder template; 24 public String OutputPath { get; set; } 25 26 public Manager(ITextTemplatingEngineHost host, StringBuilder template, bool commonHeader) { 27 this.host = host; 28 this.template = template; 29 OutputPath = String.Empty; 30 strategy = ManagementStrategy.Create(host); 31 } 32 33 public void StartBlock(String name) { 34 currentBlock = new Block { Name = name, Start = template.Length }; 35 } 36 37 public void StartFooter() { 38 footerBlock.Start = template.Length; 39 } 40 41 public void EndFooter() { 42 footerBlock.Length = template.Length - footerBlock.Start; 43 } 44 45 public void StartHeader() { 46 headerBlock.Start = template.Length; 47 } 48 49 public void EndHeader() { 50 headerBlock.Length = template.Length - headerBlock.Start; 51 } 52 53 public void EndBlock() { 54 currentBlock.Length = template.Length - currentBlock.Start; 55 blocks.Add(currentBlock); 56 } 57 58 public void Process(bool split) { 59 String header = template.ToString(headerBlock.Start, headerBlock.Length); 60 String footer = template.ToString(footerBlock.Start, footerBlock.Length); 61 blocks.Reverse(); 62 foreach(Block block in blocks) { 63 String fileName = Path.Combine(OutputPath, block.Name); 64 if (split) { 65 String content = header + template.ToString(block.Start, block.Length) + footer; 66 strategy.CreateFile(fileName, content); 67 template.Remove(block.Start, block.Length); 68 } else { 69 strategy.DeleteFile(fileName); 70 } 71 } 72 } 73 } 74 75 class ManagementStrategy 76 { 77 internal static ManagementStrategy Create(ITextTemplatingEngineHost host) { 78 return (host is IServiceProvider) ? new VSManagementStrategy(host) : new ManagementStrategy(host); 79 } 80 81 internal ManagementStrategy(ITextTemplatingEngineHost host) { } 82 83 internal virtual void CreateFile(String fileName, String content) { 84 File.WriteAllText(fileName, content); 85 } 86 87 internal virtual void DeleteFile(String fileName) { 88 if (File.Exists(fileName)) 89 File.Delete(fileName); 90 } 91 } 92 93 class VSManagementStrategy : ManagementStrategy 94 { 95 private EnvDTE.ProjectItem templateProjectItem; 96 97 internal VSManagementStrategy(ITextTemplatingEngineHost host) : base(host) { 98 IServiceProvider hostServiceProvider = (IServiceProvider)host; 99 if (hostServiceProvider == null) 100 throw new ArgumentNullException("Could not obtain hostServiceProvider"); 101 102 EnvDTE.DTE dte = (EnvDTE.DTE)hostServiceProvider.GetService(typeof(EnvDTE.DTE)); 103 if (dte == null) 104 throw new ArgumentNullException("Could not obtain DTE from host"); 105 106 templateProjectItem = dte.Solution.FindProjectItem(host.TemplateFile); 107 } 108 109 internal override void CreateFile(String fileName, String content) { 110 base.CreateFile(fileName, content); 111 ((EventHandler)delegate { templateProjectItem.ProjectItems.AddFromFile(fileName); }).BeginInvoke(null, null, null, null); 112 } 113 114 internal override void DeleteFile(String fileName) { 115 ((EventHandler)delegate { FindAndDeleteFile(fileName); }).BeginInvoke(null, null, null, null); 116 } 117 118 private void FindAndDeleteFile(String fileName) { 119 foreach(EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems) { 120 if (projectItem.get_FileNames(0) == fileName) { 121 projectItem.Delete(); 122 return; 123 } 124 } 125 } 126 }#>