我感觉CodeSmith对于我的最大用途是不用我手动创建每个表的ModelBLLDAL了,那些繁琐的工作真的让我很无语。

CodeSmith要读取数据库中的表就要先连接数据库。

新建一个数据库连接,会让你输入数据库名、数据库类型和连接字符串。我经常用到的两个连接设置如下:

数据库

连接类型

连接字符串

MySql

MySqlShemaProvider

server=localhost;database=;User Id=root;Password=123;

SqlServer

SqlShemaProvider

server=.\SQLExpress;database=;uid=sa;pwd=sa;

测试连通了以后就可以开始我们的模板路程了。

<%@ Assembly Name="SchemaExplorer" %>

<%@ Import Namespace="SchemaExplorer" %>

引用了CodeSmith自带的一个数据库连接组件,然后引用其命名空间。接下来就要定义一个属性来获取表了

<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="" Description="要操作的表" %>

他会在属性栏里边创建一个数据库选择按钮,用它来选择我们要操作的数据库。

 

Type 在这里的类型是SchemaExplorer.TableSchema 就是读取表结构,与之类似的

SchemaExplorer.DateSchema 读数据库SchemaExplorer.ViewSchema 读视图等等……

用它来选择完要操作的表以后我们就要读取表结构了,跟读取字段属性一样,都是用<%=  %>标记来取值,中间跟着字段名和他的属性,Like<%= SourceTable.Name %>去数据库名。

就想定义的模板语言一样,可以使用C#中的foreach循环来读取表的字段。使用方法如下

<%foreach(ColumnSchema col in SourceTable.Columns) {%>

<%= col.Name %>--<%= col.DataType %>

<%} %>

这样就可以循环表中所有的字段了,当然你也可以加一些条件,比如不读取主键或只读主键之类。

最终模板:

 

<%-- 

Name: 测试模板2

Author: GodFinal

Description: 

--%>

<%@ Template Language="C#" TargetLanguage="SQL" Description="连接SQL数据库,并读取表结构" Debug="True"%>

<%--调用CodeSmith自带的组件SchemaExplorer,这是一个访问数据库的组件--%>

<%@ Assembly Name="SchemaExplorer" %>

<%@ Import Namespace="SchemaExplorer" %>

<%--定义一个属性,来获得要操作的表。TableSchema取得是表,ViewSchema是视图。--%>

<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="" Description="要操作的表" %>

<%--循环读取表的字段结构--%>

<%foreach(ColumnSchema col in SourceTable.Columns) {%>

<%= col.Name %>--<%= col.DataType %>

<%} %>

测试运行结果:

 

id--Int32

CPlace--String

Saler--String

Company--String

Department--String

Account--String

telephone--String

email--String

Address--String

Zipcode--String

Level--String

 

posted on 2014-01-08 16:18  GodFinal  阅读(1228)  评论(0编辑  收藏  举报