CodeSmith模板
CodeSmith的模板默认是放在用户目录下的,在安装的时候可以自定义:
D:\Users\admin\Documents\CodeSmith Generator\Templates
上次放在c盘电脑重装就没有了,好多模板都丢失了,于是又得重新写,为了方便就记到博客园里吧。
<%-- Name: Author: mythsky Created:<%=Datetime.Now.ToShortDateString() %> Description: --%> <%@ Template Language="C#" TargetLanguage="C#" %> <%@ Assembly Name="SchemaExplorer" %> <%@ Import Namespace="SchemaExplorer" %> <%@ Import Namespace="System.Collections" %> <%@ Import Namespace="System.Text" %> <%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="数据库" %> <%@ Property Name="NameSpace" Type="String" Description="命名空间" %> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using UCredit.Common.Mapping; namespace <%=NameSpace %> { [DataMapping(ObjectId = "<%=ConvertTablename2Pascal(SourceTable) %>")] [TableMapping(Name = "<%=SourceTable.Name %>")] public partial class <%=ConvertTablename2Pascal(SourceTable) %> { <%foreach(ColumnSchema col in SourceTable.Columns){ %> /// <summary> /// <%=col.Description %> /// </summary> <%if(col.NativeType=="timestamp"){ %> [FieldMapping(Power = PowerDmlEnum.None, FieldName = "last_time")] public <%=GetCSharpVariableType(col) %> <%=Convert2Pascal(col) %> {get;set;} <%}else { %> public <%=GetCSharpVariableType(col) %> <%=Convert2Pascal(col) %> {get;set;} <%} %> <%} %> public <%=ConvertTablename2Pascal(SourceTable) %>() { } } } <script runat="template"> public string Convert2Pascal(ColumnSchema col) { StringBuilder sb = new StringBuilder(); string[] strs = col.Name.Split(new char[] { '_'}); foreach (string str in strs) { sb.Append(str.Substring(0,1).ToUpper()); sb.Append(str.Substring(1)); } return sb.ToString(); } public string ConvertTablename2Pascal(TableSchema table) { StringBuilder sb = new StringBuilder(); string[] strs = table.Name.Split(new char[] { '_'}); int index=0; foreach (string str in strs) { if(index==0) { index++; continue; } sb.Append(str.Substring(0,1).ToUpper()); sb.Append(str.Substring(1)); } return sb.ToString(); }
public string GetCSharpVariableType(ColumnSchema column) { if (column.Name.EndsWith("TypeCode")) return column.Name; 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 "short"; case DbType.UInt32: return "int"; case DbType.UInt64: return "long"; case DbType.VarNumeric: return "decimal"; default: { return "__UNKNOWN__" + column.NativeType; } } } </script>
解决CodeSmith无法读取MySQL表注释和字段注释方法:
用附件中的SchemaExplorer.MySQLSchemaProvider.dll替换此目录中的:
\Program Files (x86)\CodeSmith\v7.0\SchemaProviders
CodeSmith 判断字段可空:
public string GetNullPreString(ColumnSchema column) { if(column.AllowDBNull&&column.SystemType.IsValueType) return "?"; else return ""; }
上面的代码可以作如下改造:
public <%=GetCSharpVariableType(col) %><%=GetNullPreString(col) %> <%=Convert2Pascal(col) %> {get;set;}
其实上面转类型的方法在Codesmith的基本模板里是有的:
需要引入基本模板:
<%@ Assembly Name="Codesmith.BaseTemplates" %> <%@ Import Namespace="CodeSmith.BaseTemplates" %>
然后就可以继承SqlCodeTemplate
<%@ Template Language="C#" TargetLanguage="C#" Inherits="SqlCodeTemplate" %>
之后就能调用GetCSharpVariableType方法了:
<%foreach(ColumnSchema col in SourceTable.Columns){ %> /// <summary> /// <%=col.Description %> /// </summary> public <%=GetCSharpVariableType(col) %> <%=col.Name %> {get;set;} <%} %>
Model:

<%-- Name: Author: maomao Created:<%=Datetime.Now.ToShortDateString() %> Description: --%> <%@ Template Language="C#" TargetLanguage="C#" Inherits="SqlCodeTemplate" %> <%@ Assembly Name="Codesmith.BaseTemplates" %> <%@ Assembly Name="SchemaExplorer" %> <%@ Import Namespace="SchemaExplorer" %> <%@ Import Namespace="CodeSmith.BaseTemplates" %> <%@ Import Namespace="System.Collections" %> <%@ Import Namespace="System.Text" %> <%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="数据库" %> <%@ Property Name="NameSpace" Type="String" Description="命名空间" %> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; namespace <%=NameSpace %> { [Serializable] public partial class <%=ConvertTablename2Pascal(SourceTable) %> { #region 属性 <%foreach(ColumnSchema col in SourceTable.Columns){ %> /// <summary> /// <%=col.Description %> /// </summary> public <%=GetCSharpVariableType(col) %> <%=col.Name %> {get;set;} <%} %> #endregion public <%=ConvertTablename2Pascal(SourceTable) %>() { } public <%=ConvertTablename2Pascal(SourceTable) %>(DataRow dr) { <%foreach(ColumnSchema col in SourceTable.Columns){ %> if(dr["<%=col.Name %>"]!=DBNull.Value) { this.<%=col.Name %>= (<%=GetCSharpVariableType(col) %>)dr["<%=col.Name %>"]; } <%} %> } } } <script runat="template"> public string Convert2Pascal(ColumnSchema col) { StringBuilder sb = new StringBuilder(); string[] strs = col.Name.Split(new char[] { '_'}); foreach (string str in strs) { sb.Append(str.Substring(0,1).ToUpper()); sb.Append(str.Substring(1)); } return sb.ToString(); } public string ConvertTablename2Pascal(TableSchema table) { StringBuilder sb = new StringBuilder(); string[] strs = table.Name.Split(new char[] { '_'}); int index=0; foreach (string str in strs) { // if(index==0) // { // index++; // continue; // } sb.Append(str.Substring(0,1).ToUpper()); sb.Append(str.Substring(1)); } return sb.ToString(); } </script>
DAL:

<%-- Name: Author: maomao Created:<%=Datetime.Now.ToShortDateString() %> Description: --%> <%@ Template Language="C#" TargetLanguage="C#" Inherits="SqlCodeTemplate" %> <%@ Assembly Name="SchemaExplorer" %> <%@ Assembly Name="CodeSmith.BaseTemplates" %> <%@ Import Namespace="CodeSmith.BaseTemplates" %> <%@ Import Namespace="SchemaExplorer" %> <%@ Import Namespace="System.Collections" %> <%@ Import Namespace="System.Text" %> <%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="数据库" %> <%@ Property Name="NameSpace" Type="String" Description="命名空间" %> using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace <%=NameSpace %> { public static partial class <%=SourceTable.Name %>DAL { public static List<<%=SourceTable.Name %>> Search(string sqlStr,List<SqlParameter> pms) { List<<%=SourceTable.Name %>> list = new List<<%=SourceTable.Name %>>(); DataTable table = SqlHelper.ExecuteDataTable(sqlStr,pms.ToArray()); foreach (DataRow dr in table.Rows) { <%=SourceTable.Name %> model = new <%=SourceTable.Name %>(dr); list.Add(model); } return list; } public static bool Insert(<%=SourceTable.Name %> model) { string sqlStr = ""; List<string> fileds = new List<string>(); List<string> pFileds = new List<string>(); List<SqlParameter> pms = new List<SqlParameter>(); #region 添加参数 <%foreach(ColumnSchema col in SourceTable.Columns){ %> <%if((bool)(col.ExtendedProperties["CS_IsIdentity"].Value)==true){continue;} %> <%if(col.SystemType==typeof(DateTime)) { %> if(model.<%=col.Name %>!=null&&model.<%=col.Name %>!=new DateTime()) { fileds.Add("[<%=col.Name %>]"); pFileds.Add("@<%=col.Name %>"); pms.Add(new SqlParameter("<%=col.Name %>",SqlDbType.<%=GetSqlDbType(col) %>,<%=col.Size %>){Value=model.<%=col.Name %>}); } <% }else {%> <%if(!col.SystemType.IsValueType){ %> if(model.<%=col.Name %>!=null) { fileds.Add("[<%=col.Name %>]"); pFileds.Add("@<%=col.Name %>"); pms.Add(new SqlParameter("<%=col.Name %>", SqlDbType.<%=GetSqlDbType(col) %>,<%=col.Size %>){Value=model.<%=col.Name %>}); } <%} else{%> { fileds.Add("[<%=col.Name %>]"); pFileds.Add("@<%=col.Name %>"); pms.Add(new SqlParameter("<%=col.Name %>", SqlDbType.<%=GetSqlDbType(col) %>,<%=col.Size %>){Value=model.<%=col.Name %>}); } <%} %> <%} %> <%} %> #endregion StringBuilder sb = new StringBuilder(); sb.Append("INSERT INTO <%=SourceTable.Name %> ("); sb.Append(string.Join(",", fileds)); sb.Append(") values ("); sb.Append(string.Join(",", pFileds)); sb.Append(")"); sqlStr = sb.ToString(); int i= SqlHelper.ExecuteNonQuery(sqlStr, pms.ToArray()); return i>0; } public static bool Update(<%=SourceTable.Name %> model) { string sqlStr = ""; List<string> fileds = new List<string>(); List<string> pFileds = new List<string>(); List<SqlParameter> pms = new List<SqlParameter>(); #region 添加参数 <%foreach(ColumnSchema col in SourceTable.Columns){ %> <%if(col.IsPrimaryKeyMember){ %> pFileds.Add("[<%=col.Name %>]=@<%=col.Name %>"); pms.Add(new SqlParameter("<%=col.Name %>", SqlDbType.<%=GetSqlDbType(col) %>,<%=col.Size %>){Value=model.<%=col.Name %>}); <%} else{%> <%if(col.SystemType==typeof(DateTime)){ %> if(model.<%=col.Name %>!=null&&model.<%=col.Name %>!=new DateTime()) { fileds.Add("[<%=col.Name %>]=@<%=col.Name %>"); pms.Add(new SqlParameter("<%=col.Name %>", SqlDbType.<%=GetSqlDbType(col) %>,<%=col.Size %>){Value=model.<%=col.Name %>}); } <% }else {%> <%if(!col.SystemType.IsValueType){ %> if(model.<%=col.Name %>!=null) { fileds.Add("[<%=col.Name %>]=@<%=col.Name %>"); pms.Add(new SqlParameter("<%=col.Name %>", SqlDbType.<%=GetSqlDbType(col) %>,<%=col.Size %>){Value=model.<%=col.Name %>}); } <%} else{%> fileds.Add("[<%=col.Name %>]=@<%=col.Name %>"); pms.Add(new SqlParameter("<%=col.Name %>", SqlDbType.<%=GetSqlDbType(col) %>,<%=col.Size %>){Value=model.<%=col.Name %>}); <%} %> <%} %> <%} %> <%} %> #endregion StringBuilder sb = new StringBuilder(); sb.Append("update <%=SourceTable.Name %> set "); sb.Append(string.Join(",", fileds)); sb.Append(" where "); sb.Append(string.Join(" and ", pFileds)); sqlStr = sb.ToString(); int i= SqlHelper.ExecuteNonQuery(sqlStr, pms.ToArray()); return i>0; } } } <script runat="template"> public string Convert2Pascal(string name) { StringBuilder sb = new StringBuilder(); string[] strs = name.Split(new char[] { '_'}); foreach (string str in strs) { sb.Append(str.Substring(0,1).ToUpper()); sb.Append(str.Substring(1)); } return sb.ToString(); } public string ConvertTablename2Pascal(TableSchema table) { StringBuilder sb = new StringBuilder(); string[] strs = table.Name.Split(new char[] { '_'}); int index=0; foreach (string str in strs) { // if(index==0) // { // index++; // continue; // } sb.Append(str.Substring(0,1).ToUpper()); sb.Append(str.Substring(1)); } return sb.ToString(); } </script>
Mapping:

<%-- Name: Author: maomao Created:<%=Datetime.Now.ToShortDateString() %> Description: --%> <%@ Template Language="C#" TargetLanguage="C#" Inherits="SqlCodeTemplate" %> <%@ Assembly Name="Codesmith.BaseTemplates" %> <%@ Assembly Name="SchemaExplorer" %> <%@ Import Namespace="SchemaExplorer" %> <%@ Import Namespace="CodeSmith.BaseTemplates" %> <%@ Import Namespace="System.Collections" %> <%@ Import Namespace="System.Text" %> <%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="数据库" %> <%@ Property Name="NameSpace" Type="String" Description="命名空间" %> using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace <%=NameSpace %> { public partial class <%=SourceTable.Name %>Map:EntityTypeConfiguration<<%=SourceTable.Name %>> { public <%=SourceTable.Name %>Map() { this.ToTable("<%=SourceTable.Name %>"); <%if(SourceTable.HasPrimaryKey){ %> this.HasKey(t => new { <%foreach(ColumnSchema col in SourceTable.Columns){ %> <%if(col.IsPrimaryKeyMember){ %> t.<%=col.Name %>, <%} %> <%} %> }); <%} %> <%foreach(ColumnSchema col in SourceTable.Columns){ %> <%if((bool)col.ExtendedProperties["CS_isIdentity"].Value){ %> this.Property(t => t.<%=col.Name %>).HasColumnName("<%=col.Name %>").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); <%}else{ %> <%if(GetCSharpVariableType(col)=="string"&&col.Size!=-1) {%> this.Property(t => t.<%=col.Name %>).HasColumnName("<%=col.Name %>").HasMaxLength(<%=col.Size %>); <%}else{ %> this.Property(t => t.<%=col.Name %>).HasColumnName("<%=col.Name %>"); <%} %> <%} %> <%} %> } } } <script runat="template"> public string Convert2Pascal(ColumnSchema col) { StringBuilder sb = new StringBuilder(); string[] strs = col.Name.Split(new char[] { '_'}); foreach (string str in strs) { sb.Append(str.Substring(0,1).ToUpper()); sb.Append(str.Substring(1)); } return sb.ToString(); } </script>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述