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
附件地址:MySQLSchemaProvider.dll
CodeSmith 判断字段可空:
public string GetNullPreString(ColumnSchema column){if(column.AllowDBNull&&column.SystemType.IsValueType)return "?";elsereturn "";}
上面的代码可以作如下改造:
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;}<%} %>
API参考
方法参考
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;}<%} %>#endregionpublic <%=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>
View Code
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 %>});}<%} %><%} %><%} %>#endregionStringBuilder 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 %>});<%} %><%} %><%} %><%} %>#endregionStringBuilder 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>
View Code
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>
View Code
转载于:https://www.cnblogs.com/uptothesky/p/5488191.html
CodeSmith模板相关推荐
- DNN 4.x CodeSmith模板
写在文章之前: 使用CodeSmith模板适合对DNN模块开发了解比较深入的人员,如果你是初学者,建议先不要采用这个方式,这篇文章也可暂时跳过.初学者可以从这里开始: DotNetNuke模块制作Su ...
- 我写的第一个CodeSmith模板(添加修改数据页面)
这是我用CodeSmith的一个页面添加修改数据表的模板 .CS 1<%@ CodeTemplate Language="C#" TargetLanguage=" ...
- 对使用CodeSmith模板生成NHibernate的代码的分析
CodeSmith是我们常用的代码生成工具,其跟据不同的模板生成不同代码的方式能大大加快我们的项目开发,减少重复劳动.NHibernate模板就是其常用模板之一.从这里可以下载到最新的模板文件.现在最 ...
- codesmith 模板
近来 两天自身 写了个基本 的ORM框架,特别的Easy,但是没有相应的代码生成工具,于是就很杯具了! 于是乎,花费了一天的时间学习并写了一个CodeSmith可以运用 的模板.在此记录下CodeSm ...
- CodeSmith模板(生成实体类)
CodeSmith是一款与数据库相关的工具,只要与数据库相关的类都可以通过它编写模板来批量实现. <%@ Template Language="C#" TargetLangu ...
- codesmith 模板 html5,js-template-art【二】语法(示例代码)
一.模板语法 1.变量使用与输出 或: {{ifuser}} {{user.name}} {{/if}} art-template 同时支持 {{expression}} 简约语法与任意 JavaSc ...
- CodeSmith将模板文件批量生成文件的方法
以前写codeSmith模板的时候,如果直接像asp一样混排编写的话,代码输出来codeSmith中,不知道怎么保存到文件,后来把所有要输出的模板文字都用stringBuiler串接起来然后IO到文件 ...
- codesmith php模板,CodeSmith 基本语法-CodeTemplate 指令
基本语法-CodeTemplate 指令 前面的几篇介绍了使用 CodeSmith 模板自动生成代码和编写代码模板的基本知识.也说过 CodeSmith最核心的部分是代码模板,从本篇开始介绍 Code ...
- CodeSmith(2):对象和控制台
CodeSmith对象 代码模板对象(CodeTemplate Object) 在模板中,"this"(或者"Me"在VB.NET中)在当前模板中代码代码模板对 ...
- codesmith学习总结
code smith 使用介绍 利用CodeSmith为SQL Server CE生成项目代码 摘要:CodeSmith是很多.NET开发人员至爱的开发辅助工具,它能够使开发人员从大量枯燥无味的重 ...
最新文章
- web项目答辩总结_web实战项目遇到问题总结探索
- .NET Core2.1下采用EFCore比较原生IOC、AspectCore、AutoFac之间的性能
- 小人大作战v0.02原型(单机)发布
- css 实现table 隔行变色
- 节后如何快速进入工作状态
- diamond operator is not supported in -source 1.5和source release 8 requires target release 1.8的问题
- structure101_使用structure101分析软件包的依赖关系
- oracle两个表合并 sql,如何创建从两个表(Oracle DBMS)生成“合并”数据集的Select SQL语句?...
- 【转】DELPHI 对DICOM中的窗宽、窗位调整
- roc曲线怎么绘制_ROC曲线和PR曲线
- JeeWx捷微 2.4.1版本发布,开源JAVA微信管家平台(支持公众号、企业号)
- python 依赖包迁移(本地安装)
- python 翻译库本地库_利用python爬取并翻译GEO数据库
- java做h5小游戏服务端_神藏西游H5游戏源码服务端+客户端+搭建教程
- MSDEV.EXE 版本
- 如何解决SQL server 恢复挂起状态
- php+ioncube',windows下php安装ionCube
- 微软邮箱(@outlook.com/@hotmail.com):双重验证+应用密码
- 学会写作...【笔记】
- 梦幻西游藏宝阁不显示服务器,玩转梦幻西游藏宝阁全服搜索功能体验
热门文章
- 移动安全-IOS越狱
- android 界面置顶,Android实现界面滚动时顶部部分内容置顶(附源码)
- 索尼z3c d5833港版救砖强刷说明
- 安卓开发使用ttf文字_Android应用使用自定义字体
- 图像的灰度化和二值化
- Canon iC MF8350Cdn打印机驱动安装,解决内存不能为written问题
- 单片机蜂鸣器发出叮咚c语言程序,单片机门铃程序设计 按键按下触发蜂鸣器门铃“叮咚”响...
- 吕书健 我考H3CIE的经历
- c标准库中scanf用法
- linux ftp命令大全,linux 操作 ftp 常用命令