当前位置:
首页 > temp > 简明python教程 >
-
C# ORM学习笔记:T4入门及生成数据库实体类(2)
符号枚举
/// </summary>
public enum Symbol
{
Normal = 1,
Underline = 2
}
#endregion
#>
DBSchema.ttinclude主要实现了数据库工厂的功能。注:请将数据库连接字符串改成您自己的。
<#@ assembly name="System.Core" #> <#@ assembly name="System.Data" #> <#@ assembly name="EnvDTE" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Text" #> <#@ import namespace="System.Collections.Generic" #> <#@ import namespace="System.Data"#> <#@ import namespace="System.IO"#> <#@ import namespace="Microsoft.VisualStudio.TextTemplating"#> <#+ // T4 Template Block manager for handling multiple file outputs more easily. // Copyright (c) Microsoft Corporation.All rights reserved. // This source code is made available under the terms of the Microsoft Public License (MS-PL) // Manager class records the various blocks so it can split them up class Manager { public struct Block { public string Name; public int Start, Length; } public List<Block> blocks = new List<Block>(); public Block currentBlock; public Block footerBlock = new Block(); public Block headerBlock = new Block(); public ITextTemplatingEngineHost host; public ManagementStrategy strategy; public StringBuilder template; public string OutputPath { get; set; } public Manager(ITextTemplatingEngineHost host, StringBuilder template, bool commonHeader) { this.host = host; this.template = template; OutputPath = string.Empty; strategy = ManagementStrategy.Create(host); } public void StartBlock(string name) { currentBlock = new Block { Name = name, Start = template.Length }; } public void StartFooter() { footerBlock.Start = template.Length; } public void EndFooter() { footerBlock.Length = template.Length - footerBlock.Start; } public void StartHeader() { headerBlock.Start = template.Length; } public void EndHeader() { headerBlock.Length = template.Length - headerBlock.Start; } public void EndBlock() { currentBlock.Length = template.Length - currentBlock.Start; blocks.Add(currentBlock); } public void Process(bool split) { string header = template.ToString(headerBlock.Start, headerBlock.Length); string footer = template.ToString(footerBlock.Start, footerBlock.Length); blocks.Reverse(); foreach(Block block in blocks) { string fileName = Path.Combine(OutputPath, block.Name); if (split) { string content = header + template.ToString(block.Start, block.Length) + footer; strategy.CreateFile(fileName, content); template.Remove(block.Start, block.Length); } else { strategy.DeleteFile(fileName); } } } } class ManagementStrategy { internal static ManagementStrategy Create(ITextTemplatingEngineHost host) { return (host is IServiceProvider) ? new VSManagementStrategy(host) : new ManagementStrategy(host); } internal ManagementStrategy(ITextTemplatingEngineHost host) { } internal virtual void CreateFile(string fileName, string content) { File.WriteAllText(fileName, content); } internal virtual void DeleteFile(string fileName) { if (File.Exists(fileName)) File.Delete(fileName); } } class VSManagementStrategy : ManagementStrategy { private EnvDTE.ProjectItem templateProjectItem; internal VSManagementStrategy(ITextTemplatingEngineHost host) : base(host) { IServiceProvider hostServiceProvider = (IServiceProvider)host; if (hostServiceProvider == null) throw new ArgumentNullException("Could not obtain hostServiceProvider"); EnvDTE.DTE dte = (EnvDTE.DTE)hostServiceProvider.GetService(typeof(EnvDTE.DTE)); if (dte == null) throw new ArgumentNullException("Could not obtain DTE from host"); templateProjectItem = dte.Solution.FindProjectItem(host.TemplateFile); } internal override void CreateFile(string fileName, string content) { base.CreateFile(fileName, content); ((EventHandler)delegate { templateProjectItem.ProjectItems.AddFromFile(fileName); }).BeginInvoke(null, null, null, null); } internal override void DeleteFile(string fileName) { ((EventHandler)delegate { FindAndDeleteFile(fileName); }).BeginInvoke(null, null, null, null); } private void FindAndDeleteFile(string fileName) { foreach(EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems) { if (projectItem.get_FileNames(0) == fileName) { projectItem.Delete(); return; } } } } #>
MultiDocument.ttinclude主要实现了多文档的功能。
5.2、添加一个MultModelAuto.tt文本模板,代码如下:
<#@ template debug="true" hostspecific="true" language="C#" #> <#@ assembly name="System.Core" #> <#@ import namespace="System.Linq" #> <#@ import namespace="System.Text" #> <#@ import namespace="System.Collections.Generic" #> <#@ output extension=".cs" #> <#@ include file="T4Code/DBSchema.ttinclude"#> <#@ include file="T4Code/MultiDocument.ttinclude"#> <# var manager = new Manager(Host, GenerationEnvironment, true) { OutputPath = Path.GetDirectoryName(Host.TemplateFile)}; #> <# //System.Diagnostics.Debugger.Launch();//调试 var dbSchema = DBSchemaFactory.GetDBSchema(); List<string> tableList = dbSchema.GetTableList(); foreach(string tableName in tableList) { manager.StartBlock(tableName+".cs"); Table table = dbSchema.GetTableMetadata(tableName); #> //------------------------------------------------------------------------------- // 此代码由T4模板MultModelAuto自动生成 // 生成时间 <#=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")#> // 对此文件的更改可能会导致不正确的行为,并且如果重新生成代码,这些更改将会丢失。 //------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Text; namespace Project.Model { [Serializable] public class <#=tableName#> { #region Constructor public <#=tableName#>() { } public <#=tableName#>(<#=table.DataTypes#>) { <# foreach(Column c in table.Columns) { #> this.<#=c.UpperColumnName#> = <#=c.UpperColumnName#>; <# } #> } #endregion #region Attributes <# foreach(Column c in table.Columns) { #> public <#=GeneratorHelper.GetQuestionMarkByType(c.DataType)#> <#=c.UpperColumnName#> {get; set;} <# } #> #endregion #region Validator public List<string> ErrorList = new List<string>(); private bool Validator() { bool validatorResult = true; <# foreach(Column c in table.Columns) { if (!c.AllowDBNull) { if(c.DataType == GeneratorHelper.StringType) { #> if (string.IsNullOrEmpty(<#=c.UpperColumnName#>)) { validatorResult = false; ErrorList.Add("The <#=c.UpperColumnName#> should not be empty."); } <# } if(c.DataType == GeneratorHelper.DateTimeType) { #> if (<#=c.UpperColumnName#> == null) { validatorResult = false; ErrorList.Add("The <#=c.UpperColumnName#> should not be empty."); } <# } } if (c.DataType == GeneratorHelper.StringType) { #> if (<#=c.UpperColumnName#> != null && <#=c.UpperColumnName#>.Length > <#=c.MaxLength#>) { validatorResult = false; ErrorList.Add("The length of <#=c.UpperColumnName#> should not be greater then <#=c.MaxLength#>."); } <# } } #> return validatorResult; } #endregion } } <# manager.EndBlock(); } dbSchema.Dispose(); manager.Process(true); #>
代码保存后,可以看到此文件下面已按数据表生成了多个实体类文件: