火焰

valeb
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

T4 SqlSugare 多库 SqlServer Spring.Core IOC

Posted on 2023-08-14 19:32  valeb  阅读(6)  评论(0编辑  收藏  举报
SELECT 
  表名   = case when a.colorder = 1 then d.name else '' end, 
  TableDesc = case when a.colorder = 1 then isnull(f.value, '') else '' end, 
  字段序号 = a.colorder, 
  FieldName = a.name, 
  FieldDesc = isnull(g.[value], ''), 
  默认值 = isnull(e.text, '') ,  
  IsIdentity  = case when COLUMNPROPERTY(a.id, a.name, 'IsIdentity')= 1 then '' else '' end, 
  IsPrimaryKey  = case when exists(SELECT 1 FROM  sysobjects where xtype = 'PK' and parent_obj = a.id and name in (SELECT name FROM  sysindexes  WHERE  indid in( SELECT indid FROM sysindexkeys WHERE  id = a.id AND colid = a.colid))) then '' else '' end, 
  类型 = b.name, 
  占用字节数 = a.length, 
  长度 = COLUMNPROPERTY(a.id, a.name, 'PRECISION'), 
  小数位数 = isnull(  COLUMNPROPERTY(a.id, a.name, 'Scale'), 0  ), 
  允许为空 = case when a.isnullable = 1 then '' else '' end
FROM  syscolumns a 
  left join systypes b on a.xusertype = b.xusertype 
  inner join sysobjects d on a.id = d.id  and d.xtype = 'U'   and d.name<>'dtproperties' 
  left join syscomments e on a.cdefault = e.id 
  left join sys.extended_properties g on a.id = G.major_id  and a.colid = g.minor_id 
  left join sys.extended_properties f on d.id = f.major_id  and f.minor_id = 0 
where   d.name = 'ConfigInfo' order by a.id, a.colorder 

 // case "Byte[]":  byte[]

  1 <#@ assembly name="System.Core"#>
  2 <#@ import namespace="System.Collections.Generic"#>
  3 <#@ import namespace="System.IO"#>
  4 <#@ import namespace="System.Text"#>
  5 <#@ import namespace="Microsoft.VisualStudio.TextTemplating"#>
  6 <#+ 
  7     class Manager
  8     {
  9         public struct Block
 10         {
 11             public String Name;
 12             public int Start, Length;
 13         }
 14 
 15         public List<Block> blocks = new List<Block>();
 16         public Block currentBlock;
 17         public Block footerBlock = new Block();
 18         public Block headerBlock = new Block();
 19         public ITextTemplatingEngineHost host;
 20         public ManagementStrategy strategy;
 21         public StringBuilder template;
 22         public String OutputPath { get; set; }
 23         public Manager(ITextTemplatingEngineHost host, StringBuilder template, bool commonHeader)
 24         {
 25             this.host = host;
 26             this.template = template;
 27             OutputPath = String.Empty;
 28             strategy = ManagementStrategy.Create(host);
 29         }
 30         ///开始
 31         public void StartBlock(String name)
 32         {
 33             currentBlock = new Block { Name = name, Start = template.Length };
 34         }
 35 
 36         ///头部开始
 37         public void StartHeader()
 38         {
 39             headerBlock.Start = template.Length;
 40         }
 41         ///头部结束
 42         public void EndHeader()
 43         {
 44             headerBlock.Length = template.Length - headerBlock.Start;
 45         }
 46          
 47         ///底部开始
 48         public void StartFooter()
 49         {
 50             footerBlock.Start = template.Length;
 51         }
 52         ///底部结束
 53         public void EndFooter()
 54         {
 55             footerBlock.Length = template.Length - footerBlock.Start;
 56         }
 57      
 58         ///结束
 59         public void EndBlock()
 60         {
 61             currentBlock.Length = template.Length - currentBlock.Start;
 62             blocks.Add(currentBlock);
 63         }
 64         
 65         ///执行
 66         public void Process(bool split)
 67         {
 68             String header = template.ToString(headerBlock.Start, headerBlock.Length);
 69             String footer = template.ToString(footerBlock.Start, footerBlock.Length);
 70             blocks.Reverse();
 71             foreach (Block block in blocks)
 72             {
 73                 String fileName = Path.Combine(OutputPath, block.Name);  
 74                 if (split)
 75                 {
 76                     String content = header + template.ToString(block.Start, block.Length) + footer;
 77                     strategy.CreateFile(fileName, content);
 78                     template.Remove(block.Start, block.Length);
 79                 }
 80                 else
 81                 {
 82                     strategy.DeleteFile(fileName);
 83                 }
 84             }
 85         }
 86 
 87         ///数据库类型转换成C#类型
 88         public string ToClrType(string dataType, bool isNullable)
 89         {
 90             string returnType = string.Empty;
 91             switch (dataType)
 92             {
 93                 case "BigInt":
 94                     returnType = string.Format("{0}{1}", "long", isNullable ? "?" : "");
 95                     break;
 96                 case "Binary":
 97                 case "Image":
 98                 case "Timestamp":
 99                 case "VarBinary":
100                     returnType = "byte[]";
101                     break;
102                 case "Bit":
103                 case "Boolean":
104                     returnType = string.Format("{0}{1}", "bool", isNullable ? "?" : "");
105                     break;
106                 case "Char":
107                 case "NChar":
108                 case "NText":
109                 case "NVarChar":
110                 case "Text":
111                 case "VarChar":
112                 case "Xml":
113                 case "String":
114                     returnType = string.Format("{0}{1}", "string", "");
115                     break;
116                 case "DateTime":
117                 case "SmallDateTime":
118                 case "Date":
119                 case "Time":
120                 case "DateTime2":
121                     returnType = string.Format("{0}{1}", "System.DateTime", isNullable ? "?" : "");
122                     break;
123                 case "Decimal":
124                 case "Money":
125                 case "SmallMoney":
126                     returnType = string.Format("{0}{1}", "decimal", isNullable ? "?" : "");
127                     break;
128                 case "Float":
129                     returnType = string.Format("{0}{1}", "double", isNullable ? "?" : "");
130                     break;
131                 case "Int":
132                 case "Int32":
133 
134                     returnType = string.Format("{0}{1}", "int", isNullable ? "?" : "");
135                     break;
136                 case "Real":
137                     returnType = string.Format("{0}{1}", "float", isNullable ? "?" : "");
138                     break;
139                 case "UniqueIdentifier":
140                     returnType = string.Format("{0}{1}", "Guid", isNullable ? "?" : "");
141                     break;
142                 case "SmallInt":
143                     returnType = string.Format("{0}{1}", "short", isNullable ? "?" : "");
144                     break;
145                 case "TinyInt":
146                     returnType = string.Format("{0}{1}", "byte", isNullable ? "?" : "");
147                     break;
148                 case "Variant":
149                     returnType = string.Format("{0}{1}", "object", "");
150                     break;
151                 case "DateTimeOffset":
152                     returnType = string.Format("{0}{1}", "DateTimeOffset", isNullable ? "?" : "");
153                     break;
154                 default:
155                     returnType = "string";
156                     break;
157             }
158 
159             return returnType;
160         }
161     }
162 
163     class ManagementStrategy
164     {
165         
166         internal static ManagementStrategy Create(ITextTemplatingEngineHost host)
167         {
168             return (host is IServiceProvider) ? new VSManagementStrategy(host) : new ManagementStrategy(host);
169         }
170 
171         internal ManagementStrategy(ITextTemplatingEngineHost host) { }
172 
173         ///创建文件
174         internal virtual void CreateFile(String fileName, String content)
175         {
176             File.WriteAllText(fileName, content);
177         }
178         ///删除文件
179         internal virtual void DeleteFile(String fileName)
180         {
181             if (File.Exists(fileName))
182                 File.Delete(fileName);
183         }
184     }
185 
186     class VSManagementStrategy : ManagementStrategy
187     {
188         private EnvDTE.ProjectItem templateProjectItem;
189 
190         ///构造函数
191         internal VSManagementStrategy(ITextTemplatingEngineHost host) : base(host)
192         {
193             IServiceProvider hostServiceProvider = (IServiceProvider)host;
194             if (hostServiceProvider == null)
195                 throw new ArgumentNullException("Could not obtain hostServiceProvider");
196 
197             EnvDTE.DTE dte = (EnvDTE.DTE)hostServiceProvider.GetService(typeof(EnvDTE.DTE));
198             if (dte == null)
199                 throw new ArgumentNullException("Could not obtain DTE from host");
200 
201             templateProjectItem = dte.Solution.FindProjectItem(host.TemplateFile);
202         }
203 
204         ///创建文件
205         internal override void CreateFile(String fileName, String content)
206         {
207             base.CreateFile(fileName, content);
208             ((EventHandler)delegate { templateProjectItem.ProjectItems.AddFromFile(fileName); }).BeginInvoke(null, null, null, null);
209         }
210 
211         ///删除文件
212         internal override void DeleteFile(String fileName)
213         {
214             ((EventHandler)delegate { FindAndDeleteFile(fileName); }).BeginInvoke(null, null, null, null);
215         }
216 
217         ///查找并删除文件
218         private void FindAndDeleteFile(String fileName)
219         {
220             foreach (EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems)
221             {
222                 if (projectItem.get_FileNames(0) == fileName)
223                 {
224                     projectItem.Delete();
225                     return;
226                 }
227             }
228         }
229     }
230 #>
Manager
 1 <#@ assembly name="System.Core"#>
 2 <#@ import namespace="System.Collections.Generic"#>
 3 <#@ import namespace="System.IO"#>
 4 <#@ import namespace="System.Text"#>
 5 <#@ import namespace="Microsoft.VisualStudio.TextTemplating"#>
 6 
 7 <#
 8 string connectionString = "Data Source=192.168.0.36;Initial Catalog=WHQJGroupDB;User ID=server;Password=abc123;"; 
 9 
10 
11 string modelsPath=@"Game.Platform.Model\MODEL";
12 
13 string iserversPath=@"Game.Platform.IService";
14 string serversPath=@"Game.Platform.Service";
15 
16 string irepositoryPath=@"Game.Platform.IRepository";
17 string repositoryPath=@"Game.Platform.Repository";
18 
19 
20 string serversSessionPath=@"Game.Platform.Service\Session";  
21 string iserversSessionPath=@"Game.Platform.IService\ISession";
22 
23 
24 string repositorySessionPath=@"Game.Platform.Repository";
25 
26 
27 string irepositorySessionPath=@"Game.Platform.IRepository\Session";
28 
29 Dictionary<string, string> list = new Dictionary<string, string>()
30 {
31     { "WHQJAccountsDB","Data Source=192.168.0.36;Initial Catalog=WHQJAccountsDB;User ID=server;Password=abc123;"                },
32     { "WHQJAgentDB","Data Source=192.168.0.36;Initial Catalog=WHQJAgentDB;User ID=server;Password=abc123;"                      },
33     { "WHQJGameMatchDB","Data Source=192.168.0.36;Initial Catalog=WHQJGameMatchDB;User ID=server;Password=abc123;"              },
34     { "WHQJGameScoreDB","Data Source=192.168.0.36;Initial Catalog=WHQJGameScoreDB;User ID=server;Password=abc123;"              },
35     { "WHQJGroupDB","Data Source=192.168.0.36;Initial Catalog=WHQJGroupDB;User ID=server;Password=abc123;"                      },
36     { "WHQJNativeWebDB","Data Source=192.168.0.36;Initial Catalog=WHQJNativeWebDB;User ID=server;Password=abc123;"              },
37     { "WHQJPlatformDB","Data Source=192.168.0.36;Initial Catalog=WHQJPlatformDB;User ID=server;Password=abc123;"                },
38     { "WHQJPlatformManagerDB","Data Source=192.168.0.36;Initial Catalog=WHQJPlatformManagerDB;User ID=server;Password=abc123;"  },
39     { "WHQJRecordDB","Data Source=192.168.0.36;Initial Catalog=WHQJRecordDB;User ID=server;Password=abc123;"                    },
40     { "WHQJTreasureDB","Data Source=192.168.0.36;Initial Catalog=WHQJTreasureDB;User ID=server;Password=abc123;"                } 
41 };
42 #>
Configer
InitIRepository
 1 <#@ template debug="false" hostspecific="true" language="C#" #>
 2 <#@ assembly name="System.Core"#>
 3 <#@ assembly name="Microsoft.VisualStudio.Interop"#>
 4 <#@ assembly name="System.Data" #>
 5 <#@ assembly name="System.xml" #>
 6 <#@ import namespace="System.Collections.Generic" #>
 7 <#@ import namespace="System.Data.SqlClient" #>
 8 <#@ import namespace="System.Data" #>  
 9 <#@ import namespace="System.Collections.Generic"#>
10 <#@ import namespace="System.IO"#>
11 <#@ import namespace="System.Text"#>
12 <#@ import namespace="Microsoft.VisualStudio.TextTemplating"#> 
13 <#@ import namespace="System.Linq" #> 
14 <#@ import namespace="System.Web" #> 
15 <#@ include file="E:\worksplace\codes\T4\T4\Manager.tt"#>
16 <#@ include file="E:\worksplace\codes\T4\T4\Configer.tt"#> 
17 <#@ output extension=".cs" #>
18 <#   
19  foreach(var item in list )
20  {
21     SqlConnection conn = new SqlConnection(item.Value); 
22     conn.Open(); 
23     System.Data.DataTable schema = conn.GetSchema("TABLES"); 
24 
25     string tableQuery = "select * from @tableName"; 
26     SqlCommand command = new SqlCommand(tableQuery,conn); 
27     SqlDataAdapter ad = new SqlDataAdapter(command); 
28     System.Data.DataSet ds = new DataSet(); 
29 
30     string columnsQuery = @"SELECT 表名=sobj.name,字段名=scol.name,字段说明=sprop.[value] 
31     FROM syscolumns as scol 
32     inner join sys.sysobjects as sobj on scol.id=sobj.id and sobj.xtype='U' and sobj.name<>'dtproperties' 
33     left join sys.extended_properties as sprop on scol.id=sprop.major_id and scol.colid=sprop.minor_id 
34     where sobj.name='@tableName' and scol.name='@columnName'"; 
35 
36     SqlCommand command2 = new SqlCommand(columnsQuery,conn); 
37     SqlDataAdapter ad2 = new SqlDataAdapter(command2); 
38     System.Data.DataSet ds2 = new DataSet();
39      
40     //解决方案目录
41     string solutionDir = Host.ResolveAssemblyReference("$(SolutionDir)");
42     //当前项目目录
43     string projectDir = Host.ResolveAssemblyReference("$(ProjectDir)"); 
44     bool Generate=true;
45     var manager = new Manager(Host, GenerationEnvironment, true);
46      manager.OutputPath = $"{solutionDir}{serversPath}"; 
47 #>     
48 //<#= item.Key#>
49 namespace Game.Platform.IService 
50 {
51    using Game.Platform.Model.<#= item.Key#>;  
52  <#foreach(System.Data.DataRow row in schema.Rows)
53  {#> 
54   public partial interface I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Service  : IBaseService<Model.<#= item.Key#>.<#= row["TABLE_NAME"].ToString() #>>{ }  
55  <#}
56  #> 
57   public partial interface IBusinessSession
58   {
59  <#foreach(System.Data.DataRow row in schema.Rows){
60  #>  
61     I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Service  <#= row["TABLE_NAME"].ToString() #>_<#= item.Key#>Service { get; }
62  <#}
63  #> 
64   } 
65 }
66 <# 
67  } 
68 #>
InitIService
 1 <#@ template debug="false" hostspecific="true" language="C#" #>
 2 <#@ assembly name="System.Core"#>
 3 <#@ assembly name="Microsoft.VisualStudio.Interop"#>
 4 <#@ assembly name="System.Data" #>
 5 <#@ assembly name="System.xml" #>
 6 <#@ import namespace="System.Collections.Generic" #>
 7 <#@ import namespace="System.Data.SqlClient" #>
 8 <#@ import namespace="System.Data" #>  
 9 <#@ import namespace="System.Collections.Generic"#>
10 <#@ import namespace="System.IO"#>
11 <#@ import namespace="System.Text"#>
12 <#@ import namespace="Microsoft.VisualStudio.TextTemplating"#> 
13 <#@ import namespace="System.Linq" #> 
14 <#@ import namespace="System.Web" #> 
15 <#@ include file="E:\worksplace\codes\T4\T4\Manager.tt"#>
16 <#@ include file="E:\worksplace\codes\T4\T4\Configer.tt"#> 
17 <#@ output extension=".cs" #>
18 <#   
19  foreach(var item in list )
20  {
21     SqlConnection conn = new SqlConnection(item.Value); 
22     conn.Open(); 
23     System.Data.DataTable schema = conn.GetSchema("TABLES"); 
24 
25     string tableQuery = "select * from @tableName"; 
26     SqlCommand command = new SqlCommand(tableQuery,conn); 
27     SqlDataAdapter ad = new SqlDataAdapter(command); 
28     System.Data.DataSet ds = new DataSet(); 
29 
30     string columnsQuery = @"SELECT 表名=sobj.name,字段名=scol.name,字段说明=sprop.[value] 
31     FROM syscolumns as scol 
32     inner join sys.sysobjects as sobj on scol.id=sobj.id and sobj.xtype='U' and sobj.name<>'dtproperties' 
33     left join sys.extended_properties as sprop on scol.id=sprop.major_id and scol.colid=sprop.minor_id 
34     where sobj.name='@tableName' and scol.name='@columnName'"; 
35 
36     SqlCommand command2 = new SqlCommand(columnsQuery,conn); 
37     SqlDataAdapter ad2 = new SqlDataAdapter(command2); 
38     System.Data.DataSet ds2 = new DataSet();
39      
40     //解决方案目录
41     string solutionDir = Host.ResolveAssemblyReference("$(SolutionDir)");
42     //当前项目目录
43     string projectDir = Host.ResolveAssemblyReference("$(ProjectDir)"); 
44     bool Generate=true;
45     var manager = new Manager(Host, GenerationEnvironment, true);
46     manager.OutputPath = $"{solutionDir}{repositoryPath}"; 
47  #>   
48 //<#= item.Key#>
49 namespace Game.Platform.Repository 
50 {
51    using Game.Platform.Model.<#= item.Key#>;
52    using Game.Platform.IRepository; 
53  <#
54  foreach(System.Data.DataRow row in schema.Rows)
55  {
56  #>
57    public partial class <#= row["TABLE_NAME"].ToString() #><#= item.Key#>Repository : BaseRepository<Model.<#= item.Key#>.<#= row["TABLE_NAME"].ToString() #>>,I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Repository{ } 
58 <#
59  }
60 #>  
61   public partial class DataSession:IDataSession
62   {
63  <#foreach(System.Data.DataRow row in schema.Rows){#> 
64     private I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Repository m_I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Repository;
65     public I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Repository I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Repository
66     {
67          get
68          {
69              if(m_I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Repository==null)
70                  m_I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Repository= new <#= row["TABLE_NAME"].ToString() #><#= item.Key#>Repository();
71              return m_I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Repository;
72          } 
73     } 
74   <#}#> 
75   }
76 } 
77 <#  
78 }
79 #>
InitRepository
 1 <#@ template debug="false" hostspecific="true" language="C#" #>
 2 <#@ assembly name="System.Core"#>
 3 <#@ assembly name="Microsoft.VisualStudio.Interop"#>
 4 <#@ assembly name="System.Data" #>
 5 <#@ assembly name="System.xml" #>
 6 <#@ import namespace="System.Collections.Generic" #>
 7 <#@ import namespace="System.Data.SqlClient" #>
 8 <#@ import namespace="System.Data" #>  
 9 <#@ import namespace="System.Collections.Generic"#>
10 <#@ import namespace="System.IO"#>
11 <#@ import namespace="System.Text"#>
12 <#@ import namespace="Microsoft.VisualStudio.TextTemplating"#> 
13 <#@ import namespace="System.Linq" #> 
14 <#@ import namespace="System.Web" #> 
15 <#@ include file="E:\worksplace\codes\T4\T4\Manager.tt"#>
16 <#@ include file="E:\worksplace\codes\T4\T4\Configer.tt"#> 
17 <#@ output extension=".cs" #>
18 <#   
19  foreach(var item in list )
20  {
21     SqlConnection conn = new SqlConnection(item.Value); 
22     conn.Open(); 
23     System.Data.DataTable schema = conn.GetSchema("TABLES"); 
24 
25     string tableQuery = "select * from @tableName"; 
26     SqlCommand command = new SqlCommand(tableQuery,conn); 
27     SqlDataAdapter ad = new SqlDataAdapter(command); 
28     System.Data.DataSet ds = new DataSet(); 
29 
30     string columnsQuery = @"SELECT 表名=sobj.name,字段名=scol.name,字段说明=sprop.[value] 
31     FROM syscolumns as scol 
32     inner join sys.sysobjects as sobj on scol.id=sobj.id and sobj.xtype='U' and sobj.name<>'dtproperties' 
33     left join sys.extended_properties as sprop on scol.id=sprop.major_id and scol.colid=sprop.minor_id 
34     where sobj.name='@tableName' and scol.name='@columnName'"; 
35 
36     SqlCommand command2 = new SqlCommand(columnsQuery,conn); 
37     SqlDataAdapter ad2 = new SqlDataAdapter(command2); 
38     System.Data.DataSet ds2 = new DataSet();
39      
40     //解决方案目录
41     string solutionDir = Host.ResolveAssemblyReference("$(SolutionDir)");
42     //当前项目目录
43     string projectDir = Host.ResolveAssemblyReference("$(ProjectDir)"); 
44     bool Generate=true; 
45     var manager = new Manager(Host, GenerationEnvironment, true);
46     manager.OutputPath = $"{solutionDir}{serversPath}";
47  #>   
48  //<#= item.Key#>
49 namespace Game.Platform.Service 
50 {
51    using Game.Platform.Model.<#= item.Key#>;  
52    using Game.Platform.IService;  
53  <#
54  foreach(System.Data.DataRow row in schema.Rows)
55  {
56  #>
57    public partial class <#= row["TABLE_NAME"].ToString() #><#= item.Key#>Service  : BaseService<Model.<#= item.Key#>.<#= row["TABLE_NAME"].ToString() #>>,I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Service 
58    { 
59      public override void SetDAL()
60      {
61         idal = M_DataSession.I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Repository;
62      }
63    } 
64  <#
65  }
66  #> 
67    public partial class BusinessSession:IBusinessSession
68    {
69  <#foreach(System.Data.DataRow row in schema.Rows){#> 
70      private I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Service  m_I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Service ;
71      public I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Service  <#= row["TABLE_NAME"].ToString() #>_<#= item.Key#>Service 
72         {
73            get
74            {
75                if(m_I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Service ==null)
76                    m_I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Service = new <#= row["TABLE_NAME"].ToString() #><#= item.Key#>Service ();
77                return m_I<#= row["TABLE_NAME"].ToString() #><#= item.Key#>Service ;
78            } 
79         }
80   <#} #> 
81   }
82  }   
83 <#  
84 }
85 #>
InitService
  1 <#@ template debug="false" hostspecific="true" language="C#" #>
  2 <#@ assembly name="System.Core"#>
  3 <#@ assembly name="Microsoft.VisualStudio.Interop"#>
  4 <#@ assembly name="System.Data" #>
  5 <#@ assembly name="System.xml" #>
  6 <#@ import namespace="System.Collections.Generic" #>
  7 <#@ import namespace="System.Data.SqlClient" #>
  8 <#@ import namespace="System.Data" #>  
  9 <#@ import namespace="System.Collections.Generic"#>
 10 <#@ import namespace="System.IO"#>
 11 <#@ import namespace="System.Text"#>
 12 <#@ import namespace="Microsoft.VisualStudio.TextTemplating"#> 
 13 <#@ import namespace="System.Linq" #> 
 14 <#@ import namespace="System.Web" #> 
 15 <#@ include file="E:\worksplace\codes\T4\T4\Manager.tt"#>
 16 <#@ include file="E:\worksplace\codes\T4\T4\Configer.tt"#> 
 17 <#@ output extension=".cs" #>
 18 <#
 19 //多数据库配置列表
 20  foreach(var item in list )
 21  { 
 22     //解决方案目录
 23     string solutionDir = Host.ResolveAssemblyReference("$(SolutionDir)");
 24     //当前项目目录
 25     string projectDir = Host.ResolveAssemblyReference("$(ProjectDir)"); 
 26     bool Generate=true;
 27     var manager = new Manager(Host, GenerationEnvironment, true);
 28     manager.OutputPath = $"{solutionDir}{modelsPath}";
 29 
 30     //查询数据库中表 生成对应的实体名称
 31     SqlConnection conn = new SqlConnection(item.Value); 
 32     conn.Open(); 
 33     System.Data.DataTable schema = conn.GetSchema("TABLES");  
 34 #>  
 35 //<#= item.Key#>
 36 namespace Game.Platform.Model.<#= item.Key#>
 37 { 
 38     using System;
 39     using SqlSugar;
 40 <#  
 41 foreach(System.Data.DataRow row in schema.Rows) 
 42 {   
 43 var table_name= row["TABLE_NAME"].ToString();
 44 #>  
 45    [TenantAttribute("<#= item.Key#>")]
 46    public class <#= table_name #>
 47    {
 48 <# 
 49 //查询下表 用来生成实体结构
 50   var tableQuery = "select * from @tableName"; 
 51     SqlCommand command = new SqlCommand(tableQuery,conn); 
 52     SqlDataAdapter ad = new SqlDataAdapter(command); 
 53     System.Data.DataSet ds = new DataSet(); 
 54     command.CommandText = tableQuery.Replace("@tableName",table_name); 
 55     ad.FillSchema(ds, SchemaType.Mapped, table_name);
 56     DataTable dt=ds.Tables[0];
 57 
 58 //查询下表特性 用来确定 标识列与主键列 以及字段说明
 59  var columnsQuery = @"SELECT  
 60   表名   = case when a.colorder = 1 then d.name else '' end, --0
 61   TableDesc = case when a.colorder = 1 then isnull(f.value, '') else '' end, --1
 62   字段序号 = a.colorder, 
 63   FieldName = a.name, --3
 64   FieldDesc = isnull(g.[value], ''), --4
 65   默认值 = isnull(e.text, '') ,  
 66   IsIdentity  = case when COLUMNPROPERTY(a.id, a.name, 'IsIdentity')= 1 then 1 else 0 end, 
 67   IsPrimaryKey  = case when exists(SELECT 1 FROM  sysobjects where xtype = 'PK' and parent_obj = a.id and name in (SELECT name FROM  sysindexes  WHERE  indid in( SELECT indid FROM sysindexkeys WHERE  id = a.id AND colid = a.colid))) then 1 else 0 end, 
 68   FieldType = b.name, 
 69   占用字节数 = a.length, 
 70   FieldLength = COLUMNPROPERTY(a.id, a.name, 'PRECISION'), 
 71   小数位数 = isnull(  COLUMNPROPERTY(a.id, a.name, 'Scale'), 0  ), 
 72   AllowDBNull = case when a.isnullable = 1 then 1 else 0 end
 73 FROM  syscolumns a 
 74   left join systypes b on a.xusertype = b.xusertype 
 75   inner join sysobjects d on a.id = d.id  and d.xtype = 'U'   and d.name<>'dtproperties' 
 76   left join syscomments e on a.cdefault = e.id 
 77   left join sys.extended_properties g on a.id = G.major_id  and a.colid = g.minor_id 
 78   left join sys.extended_properties f on d.id = f.major_id  and f.minor_id = 0 
 79 where   d.name = '@tableName' order by a.id, a.colorder ".Replace("@tableName", table_name);  
 80     SqlCommand commandCol = new SqlCommand(columnsQuery,conn); 
 81     SqlDataAdapter adCol = new SqlDataAdapter(commandCol); 
 82     System.Data.DataSet dsCol = new DataSet(); 
 83     adCol.Fill(dsCol);
 84     DataTable dtCol=dsCol.Tables[0];
 85 
 86     string PrimaryKeyFieldName = string.Empty;
 87     if (dtCol.Select("IsPrimaryKey = 1").Length > 0)
 88     {
 89          PrimaryKeyFieldName = dtCol.Select("IsPrimaryKey = 1")[0][3].ToString();
 90     } 
 91     string IdentityFieldName = string.Empty;
 92     if (dtCol.Select("IsIdentity=1").Length>0)
 93     {
 94         IdentityFieldName = dtCol.Select("IsIdentity = 1")[0][3].ToString();
 95     }  
 96  foreach (DataColumn dc in dt.Columns)
 97   {    
 98   var colName=dc.ColumnName; 
 99 #>     
100       /// <summary>
101       /// <#= dc.DataType.Name #> <#= dtCol.Select($"FieldName = '{colName}'").Length > 0 ? dtCol.Select($"FieldName ='{colName}'")[0][4].ToString().Replace("\r\n","\r\n      /// "):"" #>
102       /// </summary>   
103 <#  
104 if(colName==PrimaryKeyFieldName && colName!=IdentityFieldName)
105 {
106 #>
107     [SugarColumn(ColumnName="<#= colName #>",IsPrimaryKey = true)]
108 <#  
109 }else if(colName!=PrimaryKeyFieldName && colName==IdentityFieldName)
110 { 
111 #>
112     [SugarColumn(ColumnName="<#= colName #>",IsIdentity  = true)]
113 <# 
114 }else if(colName==PrimaryKeyFieldName && colName==IdentityFieldName)
115 { 
116 #>
117     [SugarColumn(ColumnName="<#= colName #>",IsPrimaryKey = true,IsIdentity = true)]
118 <#  
119 }else
120 { 
121 #>
122     [SugarColumn(ColumnName="<#= colName #>")]
123 <# }#>
124      public <#=manager.ToClrType(dc.DataType.Name,dc.AllowDBNull)#> <#= colName==row["TABLE_NAME"].ToString()? "_"+colName : colName #> {get;set;}
125 <# }#>
126    }
127 <# } #>
128 }
129 <# } #>
InitModel

 

见:   Spring.Core  IOC