CodeSmith简单用法

概述

平常我们在写代码的时候,一般会有很多重复的代码,比如dal、bll、实体等等,这些东西很多是重复的,网上有很多的生成工具,但是生成的东西一般不是我们直接想要的,都需要修改。这时候CodeSmith就派上用场了,CodeSmith是可以用来大量生成代码的。用起来其实也很简单,大部分的代码生成工具都是需要模板的,这个很好理解,模板就是一段代码,里面留几个洞,这个洞会被数据库的字段名或表名等填充,CodeSmith的最多的用法就是连接数据库,然后把数据库信息取出来去替换用户提供的模板中关键字,这就是代码生成的原理。

使用方式

1、安装一个最新版的codesmtih。

2、打开界面。

3、新建一个csharp的模板。

4、编写脚本,按照我之前的一个项目Service.cst为例。

<%@ CodeTemplate Language="C#" TargetLanguage="C#" Src="DataEntity.cst.cs" ResponseEncoding="UTF-8" Inherits="CodeSmith.MyTemplates.TableObjectTemplate" Description="Generate A DataTable Collection and Persis object." %><%@ Assembly Name="SchemaExplorer" %><%@ Assembly Name="SchemaExplorer.SqlSchemaProvider" %><%@ Assembly Name="System.Data" %><%@ Assembly Name="System.Design" %><%@ Import Namespace="System.Collections.Generic" %><%@ Import Namespace="System.Data" %><%@ Import Namespace="System.IO" %><%@ Import Namespace="SchemaExplorer" %>using System;using System.Collections.Generic;using System.Linq;using System.Text;using PaiXie.Data;using System.Data;using FluentData;namespace <%= Namespace %> {   public class <%= GetClassName(SourceTable, false) %>Service  : BaseService<<%= GetClassName(SourceTable, false) %>> {            #region Update            public static int Update(<%= GetClassName(SourceTable, false) %> entity, IDbContext context = null) {      return <%= GetClassName(SourceTable, false) %>Repository.GetInstance().Update(entity, context);    }                #endregion
#region Add public static int Add(<%= GetClassName(SourceTable, false) %> entity, IDbContext context = null) { return <%= GetClassName(SourceTable, false) %>Repository.GetInstance().Add(entity, context); } #endregion #region 获取单个实体 通过主键ID
/// /// 获取单个实体 通过主键ID /// /// 主键ID /// 数据库连接对象 /// public static <%= GetClassName(SourceTable, false) %> GetQuerySingleByID(int id, IDbContext context = null) { return <%= GetClassName(SourceTable, false) %>Repository.GetInstance().GetQuerySingleByID(id, context); } #endregion
#region 删除操作 通过ID
/// /// 删除操作 通过ID /// /// 主键ID /// 数据库对象 /// public static int DelByID(int id, IDbContext context = null) { return <%= GetClassName(SourceTable, false) %>Repository.GetInstance().DelByID(id, context); } #endregion }}






5、按一下F5。


请使用浏览器的分享功能分享到微信等