CodeSmith4-案例
执行子模板
Main.cst
<%@ Template Language="C#" TargetLanguage="Text" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Property Name="SourceDB" Type="DatabaseSchema" Optional="False" %>
<script runat="template">
public void RenderChild1()
{
CodeTemplateCompiler compiler = new CodeTemplateCompiler(".\\Child.cst");
compiler.Compile();
if (compiler.Errors.Count == 0)
{
CodeTemplate template = compiler.CreateInstance();
//DatabaseSchema SourceDB = new DatabaseSchema(new MySQLSchemaProvider(), @"Data Source=127.0.0.1;User Id=root;Password=xYi7sR2Ivc;Database=meshop_www;Port=33306;");
TableSchema table = SourceDB.Tables["user_info"];
template.SetProperty("SourceTable", table);
//template.Render(Response);
template.RenderToFile(".\\"+table.Name+".cs",true);
}
else
{
for (int i = 0; i < compiler.Errors.Count; i++)
{
Console.Error.WriteLine(compiler.Errors[i].ToString());
}
}
}
</script>
<%RenderChild1(); %>
Child.cst
<%@ Template Language="C#" TargetLanguage="Text" %>
<%@ Property Name="SourceTable" Type="TableSchema" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<script runat="template">
public void Output()
{
foreach(ColumnSchema column in SourceTable.Columns)
{
Response.WriteLine(column.Name);
}
}
</script>
<% Output(); %>
DB Model模板
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ CodeTemplate Language="C#" ResponseEncoding="UTF-8" Description="数据库实体模板"%>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="属性" Description="要生成实体的数据表" %>
<%@ Property Name="Namespace" Type="String" Default="Model" Category="内容" Description="命名空间名称" %>
namespace <%=Namespace%>
{
/// <summary>
///<%=SourceTable.Description %>
/// </summary>
[Serializable]
public partial class <%=GetClassName(SourceTable) %>
{
#region 常量
///<summary>
///主键ID
///</summary>
public const string <%=GetConstName(GetPrimaryKeyPropertyName(SourceTable))%> = "<%=GetPrimaryKeyPropertyName(SourceTable)%>";
<%for(int i=0;i<SourceTable.NonPrimaryKeyColumns.Count;i++) {
var column = SourceTable.NonPrimaryKeyColumns[i];
%>
///<summary>
///<%=column.Description %>
///</summary>
public const string <%=GetConstName(GetPropertyName(column)) %> = "<%=GetPropertyName(column) %>";
<%} %>
#endregion
#region 私有字段
///<summary>
///主键ID
///</summary>
private <%=GetPrimaryKeyType(SourceTable)%> <%=GetPrimaryKeyFieldName(SourceTable) %>;
<%for(int i=0;i<SourceTable.NonPrimaryKeyColumns.Count;i++) {
var column = SourceTable.NonPrimaryKeyColumns[i];
%>
private <%=GetDataType(column) %> <%=GetFieldName(column) %><%=GetDefaultValueByDBColumn(column)%>;
<%} %>
#endregion
#region 公共属性
public <%=GetPrimaryKeyType(SourceTable) %> <%=GetPrimaryKeyPropertyName(SourceTable) %> {get; set;}
<%for(int i=0;i<SourceTable.NonPrimaryKeyColumns.Count;i++) {
var column = SourceTable.NonPrimaryKeyColumns[i];
%>
///<summary>
///<%=column.Description %>
///</summary>
public <%=GetDataType(column) %> <%=GetPropertyName(column) %> {get; set;}
<%} %>
#endregion
#region 重写的方法
public override bool Equals(object obj)
{
bool result = false;
if (obj is <%=GetClassName(SourceTable)%>)
{
result = (obj as <%=GetClassName(SourceTable)%>).ID == this.ID;
}
return result;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override string ToString()
{
<%
string[] columns=new string[SourceTable.Columns.Count];
for(int i=0;i<SourceTable.Columns.Count;i++) {
var column = SourceTable.Columns[i];
columns[i] = "{"+GetPropertyName(column)+"}";
}
%>
return $"<%=string.Join(",",columns) %>";
}
#endregion
}
}
<script runat="template">
// 获取类名
public string GetClassName(TableSchema table)
{
string newTableName="";
if(table.Name.Contains("_"))
{
var words = table.Name.Split('_');
for(int i=0;i<words.Length;i++)
{
newTableName += ConvertToPascal(words[i]);
}
}
else
{
newTableName=table.Name;
}
return newTableName;
}
// 获取主键类型
public string GetPrimaryKeyType(TableSchema table)
{
return GetCSharpDataTypeByDBColumn(GetPrimaryKey(table));
}
// 获取主键属性名
public string GetPrimaryKeyPropertyName(TableSchema table)
{
return ConvertToPascal(GetPrimaryKey(table).Name);
}
// 获取主键字段名
public string GetPrimaryKeyFieldName(TableSchema table)
{
return "_"+ConvertToCamel(GetPrimaryKey(table).Name);
}
// 根据列对象获得列的类型
public string GetDataType(ColumnSchema column)
{
return GetCSharpDataTypeByDBColumn(column);
}
// 根据列对象获得列的字段名
public string GetFieldName(ColumnSchema column)
{
return "_"+ConvertToCamel(column.Name);
}
// 根据列对象获得列的属性名
public string GetPropertyName(ColumnSchema column)
{
return ConvertToPascal(column.Name);
}
// 获取常量名称
public string GetConstName(string name)
{
return "_"+name.ToUpper()+"_";
}
// 获取主键字段
public MemberColumnSchema GetPrimaryKey(TableSchema table)
{
if (table.PrimaryKey != null)
{
if (table.PrimaryKey.MemberColumns.Count == 1)
{
return table.PrimaryKey.MemberColumns[0];
}
else
{
throw new ApplicationException("此模板只支持单个列的主键");
}
}
else
{
throw new ApplicationException("此模板需要有主键的表");
}
}
//获取字段默认值
public string GetDefaultValueByDBColumn(ColumnSchema column)
{
switch (column.DataType)
{
case DbType.AnsiString:
case DbType.AnsiStringFixedLength:
case DbType.String:
case DbType.StringFixedLength: return "= \"\"";
case DbType.Date:
case DbType.DateTime: return " = new DateTime(1900,1,1)";
default:
return "";
}
}
//获取字段类型
public string GetCSharpDataTypeByDBColumn(ColumnSchema column)
{
switch (column.DataType)
{
case DbType.AnsiString: return "string";
case DbType.AnsiStringFixedLength: return "string";
case DbType.Binary: return "byte[]";
case DbType.Boolean: return "bool";
case DbType.Byte: return "byte";
case DbType.Currency: return "decimal";
case DbType.Date: return "DateTime";
case DbType.DateTime: return "DateTime";
case DbType.Decimal: return "decimal";
case DbType.Double: return "double";
case DbType.Guid: return "Guid";
case DbType.Int16: return "short";
case DbType.Int32: return "int";
case DbType.Int64: return "long";
case DbType.Object: return "object";
case DbType.SByte: return "sbyte";
case DbType.Single: return "float";
case DbType.String: return "string";
case DbType.StringFixedLength: return "string";
case DbType.Time: return "TimeSpan";
case DbType.UInt16: return "ushort";
case DbType.UInt32: return "uint";
case DbType.UInt64: return "ulong";
case DbType.VarNumeric: return "decimal";
default:
return "__UNKNOWN__" + column.NativeType;
}
}
//重写文件名
public override string GetFileName()
{
return GetClassName(SourceTable) + ".cs";
}
//Pascal命名转换
public string ConvertToPascal(string str)
{
return str.Substring(0,1).ToUpper() + str.Substring(1);
}
// 骆驼命名转换
public string ConvertToCamel(string str)
{
return str.Substring(0,1).ToLower() + str.Substring(1);
}
</script>