CodeSmith模板

article/2025/9/15 19:32:55

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


http://chatgpt.dhexx.cn/article/EFC38gE8.shtml

相关文章

CodeSmith连Oracle

据说CodeSmith连Oracle特别麻烦&#xff0c;什么WIN7下不行&#xff0c;64位下不行。之前有个同事为了用上CodeSmith&#xff0c;还特地装了个XP虚拟机。 其实&#xff0c;还是那个连接串的问题。 操作系统64位&#xff0c;就要用64位的驱程。但我们机器上装的是oracle 10g&a…

codesmith mysql 注释_完美解决CodeSmith无法获取MySQL表及列Description说明注释的方案...

问题描述&#xff1a; CodeSmith是现在比较实用的代码生成器&#xff0c;但是我们发现一个问题&#xff1a; 使用CodeSmith编写MySQL模板的时候&#xff0c;会发现一个问题&#xff1a;MySQL数据表中的列说明获取不到&#xff0c;也就是column.Description。如图&#xff1a; 我…

codesmith mysql 模板_CodeSmith for MySQL template

对于.NET平台上的代码生成器来说&#xff0c;codesmith是一个非常好的选择。 以前在学院实验室用的都是SQL server数据库&#xff0c;老师给的一套codesmith模板用来生成model/DAL/BLL很是方便。 不过后来放弃SQL server 投入MySQL之后&#xff0c;刚开始都是手写SQL&#xff0…

如何使用CodeSmith批量生成代码(原创系列教程)

用它完成批量代码生成的工作啦. 下面我会一步步的解释如何用CodeSmith实现预期的结果的,事先声明一下,在此只做一个简单的Demo,并不详细的讲解CodeSmith各个强大的功能,有兴趣的朋友可以打开CodeSmith的帮助文档了解.我只做个抛砖引玉,希望能激起大家更多思想的火花~ 先看看C…

codesmith生成SQLSERVER实体(带注释)

记录用codesmith生成SQLSERVER数据库实体的一个模板&#xff0c;具体链接数据库和使用方式&#xff0c;大家可以百度&#xff0c;有非常多的资料&#xff0c;只记录一个模板&#xff1a; <% CodeTemplate Language"C#" TargetLanguage"C#" Debug"…

mysql codesmith_CodeSmith MySql

CodeSmith MySql (2012-08-22 10:41:49) 标签&#xff1a; 杂谈 安装&#xff1a; mysql-connector-net-6.3.7.msi 否则在CodeSmith中链接数据库时提示需要框架程序。 connect string&#xff1a; 正确&#xff1a;DatabaseXXX;Data SourceXXX;User IdXXX;PasswordXXX;portXXX …

CodeSmith模板代码生成实战详解

为了提高开发效率&#xff0c;节约开发时间&#xff0c;我们采用了codesmith根据自定义模板&#xff0c;生成代码功能。让单表的增删改查功能从数据访问层到ui展示层一键批量生成。下面就开始codeSmith模板编写。 官网地址&#xff1a;http://www.codesmithtools.com 下载地址&…

CodeSmith 简单使用和常用模板

1、简介 CodeSmith 是一种基于模板的代码生成工具&#xff0c;它使用类似于 ASP.NET的语法来生成任意类型的代码或文本。 2、软件布局 整体布局和visual studio系列相似&#xff0c;用过VS开发对此软件布局会很熟悉&#xff0c;加上模板语句类似ASP.NET对.NET开发人员相对友…

CodeSmith介绍

什么是CodeSmith&#xff1f;从字面上直译可以看作“代码工匠”。这倒是个很拟人化的名称&#xff0c;顾名思义&#xff0c;CodeSmith的目标就是根据模板生成规范可用的代码&#xff0c;为程序员减轻工作负担。程序员是软件开发团队中的最小单位&#xff0c;有什么任务都只能自…

waf绕过详解

目录 waf防护原理讲解 目录扫描绕过waf 手工注入绕过waf sqlmap注入绕过waf 编写sqlmap绕过waf脚本 过waf一句话编写讲解 菜刀连接绕过waf webshell上传绕过waf 提权绕过waf waf绕过原理详解 了解waf防护原理 查看waf防护位置 熟悉防护规则 了解防护机制 查看拦截…

WAF与网络防火墙的区别在哪?

WAF是英文Web Application Firewall的简称&#xff0c;也称为网站应用级入侵防御系统或Web应用防火墙&#xff0c;是通过执行一系列针对HTTP/HTTPS的安全策略来专门为Web应用提供保护的一款产品。 网络防火墙是一种用来加强网络之间访问控制的特殊网络互联设备。计算机流入流出…

WAF(Web应用层防火墙)了解学习

WAF---Web应用层防火墙了解学习 WAF是什么WAF预防的攻击类型WAF部署方式WAF安全模式开放Web应用安全项目&#xff08;OWASP&#xff09;WAF和DDosWAF测试WAF和传统防火墙的区别总结 参考文档: 安全文章相关Web应用防火墙WAF简介 WAF是什么 WAF全称叫Web Application Firewall…

什么是 Web 应用防火墙(WAF)?

当下时候&#xff0c;网络攻击和针对网站的攻击与日俱增。同时&#xff0c;在我们的日常生活中&#xff0c;安全的重要性也迅速提升。因此&#xff0c;保证在线上世界的安全变得越来越重要。更重要的是&#xff0c;保护你的网站和所存储的数据的安全。所以&#xff0c;我们将介…

【网络安全】如何在Apache 安装开源 WAF

说明&#xff1a; 本文以Windows环境下的Apache安装mod_security为例&#xff0c; 介绍开源WAF产品的安装使用。 http://www.modsecurity.cn/ https://github.com/SpiderLabs/ModSecurity一、WAF基本介绍 WAF全称Web Application Firewall&#xff0c;即Web应用防火墙。Web应用…

WAF详解及WAF绕过

waf&#xff08;web application firewall&#xff09;: 原理&#xff1a; web应用防火墙&#xff0c;一款集网站内容安全防护、网站资源安全防护及流量保护功能为一体的服务器工具。为用户提供实时网站安全防护&#xff0c;避免各类针对网站的攻击带来的危害。&#xff08;核心…

waf入门

文章目录 waf入门什么是wafwaf一般都有哪些功能WAF部署模式WAF工作模式 规则引擎原理WAF动作WAF规则与报表WAF特征 waf入门 什么是waf Web应用防护系统&#xff08;也称为&#xff1a;网站应用级入侵防御系统。英文&#xff1a;Web Application Firewall&#xff0c;简称&…

WAF识别软件(WAFW00F)以及WAF绕过

责任声明&#xff1a; 本文章仅供学习交流使用&#xff0c;如有利用进行非法行为 上传者不承担任何责任&#xff0c;使用者后果自负 WAF防护分析 什么是WAF&#xff1f; Web应用防护系统分为两种&#xff1a;软件与硬件 安全公司内部的为硬件&#xff0c;个人或小企业为软件&…

IPS和WAF区别

写在前面&#xff1a; “前些天发现了一个巨牛的人工智能学习网站&#xff0c;通俗易懂&#xff0c;风趣幽默&#xff0c;忍不住分享一下给大家。点击跳转到网站。” 前言 - 床长人工智能教程 WAF与IPS的区别总结 谁是最佳选择&#xff1f; Web应用防护无疑是一个热门话题。…

waf详解

文章目录 一、waf分类二、waf的工作原理 前言&#xff1a; 在实际的渗透测试过程中&#xff0c;经常会碰到网站存在WAF的情况。网站存在WAF&#xff0c;意味着我们不能使用安全工具对网站进行测试&#xff0c;因为一旦触碰了WAF的规则&#xff0c;轻则丢弃报文&#xff0c;重则…

waf测试

waf简介 WAF防火墙其实就是Web Application Firewall&#xff0c;是一个web应用防护系统。企业等用户一般采用防火墙作为安全保障体系的第一道防线。WAF工作在应用层&#xff0c;因此对Web应用防护具有先天的技术优势。基于对Web应用业务和逻辑的深刻理解&#xff0c;WAF对来自…