类型映射字典

类型映射字典

首先 CodeSmith 的字典映射是定义一些用来映射的对照字典。比如数据库里面的 nvarchar 映射到 C# 里面的 string。不过 CodeSmith 官方已经内置了一个映射表:

<%--引入system类型转为c#的数据类型的映射字典 --%>
<%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="System to C# Type Map" %>Code language: HTML, XML (xml)

我们需要把它引入:

<%--声明数据库的参数,在左下角的Database属性中,选择要操作的数据库名称--%>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Optional="True" Category="Context" Description="Table to get the data from." %>

<%--引入下面的类库,操作数据库必备的。不要纠结加入就行啦。--%>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>

<%--引入system类型转为c#的数据类型的映射字典 --%>
<%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="System to C# Type Map" %>Code language: HTML, XML (xml)

遍历数据库表的字段属性(未使用字典)

<% foreach (ColumnSchema column in this.SourceTable.Columns) {  %>
<%--拼接字符串,输出c#中实体的属性--%>
public <%= column.SystemType.FullName %> <%= column.Name %>{ get; set; }

<% } %>Code language: HTML, XML (xml)

生成结果:

public System.Int32 AccountID{ get; set; }

public System.Int32 UniqueID{ get; set; }

public System.String Email{ get; set; }

public System.String FirstName{ get; set; }

public System.String LastName{ get; set; }

public System.String Address1{ get; set; }

public System.String Address2{ get; set; }

public System.String City{ get; set; }

public System.String State{ get; set; }

public System.String Zip{ get; set; }

public System.String Country{ get; set; }

public System.String Phone{ get; set; }Code language: JavaScript (javascript)

使用字典

<%--遍历数据库表的字段属性--%>
<% foreach (ColumnSchema column in this.SourceTable.Columns) {  %>
<%--拼接字符串,输出c#中实体的属性--%>
public <%= CSharpAlias[column.SystemType.FullName] %> <%= column.Name %>{ get; set; }

<% } %>Code language: HTML, XML (xml)

生成结果:

public int AccountID{ get; set; }

public int UniqueID{ get; set; }

public string Email{ get; set; }

public string FirstName{ get; set; }

public string LastName{ get; set; }

public string Address1{ get; set; }

public string Address2{ get; set; }

public string City{ get; set; }

public string State{ get; set; }

public string Zip{ get; set; }

public string Country{ get; set; }

public string Phone{ get; set; }Code language: JavaScript (javascript)

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注